reactjs / reactjs/react.dev

Confusing setState() documentation

オープン
#715 コメント 8 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
JavaScript
スター
11.8k
フォーク
7.9k
平均マージ
1日 11時間
マージ済み PR(30日)
11

説明

I have a general question about setState() because the documentation about this is a little bit confusing:

I have a component with a state. This state should only be updated (re-rendered) when a condition met. If not then there is no need to re-render the component. Reading the docs about setState tells me that reading this.state right after calling setState() is a potential pitfall. Instead I should use setState with an updater function because there prevState is guaranteed to has the right value. So my first approach was:

class MyComponent extends React.Component {
  onSomething = () => {
    this.setState(prevState => {
      if (prevState.counter < 10) {
        return { counter: prevState.counter + 1 };
      }
      return prevState;
    });
  }
}

But with that approach my component always get re-rendered because setState() always forces a re-render (in the beginning I thought that when I return the same prevState object React does nothing. But I was wrong). So what else can I do to avoid re-rendering?

Again in the same doc we can read that calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders. So I could re-write my code into following:

class MyComponent extends React.Component {
  onSomething = () => {
    if (this.state.counter < 10) {
      this.setState(prevState => {
        return { counter: prevState.counter + 1 };
      });
    }
  }
}

But then if (this.state.counter < 10) could have a different value than prevState.counter

So on the one side the docs recommend to not read from this.state directly because the calls to setState() could be batched and this.state has an outdated value but on the other side it recommends to call setState() only when the new state differs from the old state. But how can I check if the state differs when it could be potentially outdated?

In the end I don't know actually how to set my state and avoid a re-rerender when a condition met. Any help here would be great.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされた setState() のドキュメントとこの issue の例から始め、その後、updater 関数、バッチ処理、再レンダリングがどのように説明されているかを確認します。条件が満たされたときに不要な再レンダリングを避ける方法を説明し、見かけ上の矛盾をドキュメントが明確に解消できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。