reactjs / reactjs/react.dev

A note about not firing side effects in useState(prev => next) ?

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

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

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

説明

So I ended up doing this by mistake after a wonky merge:

let Foo = (props) => {
    let [bar, setBar] = useState();
    
    let handleClick = () => {
        useState(bar => {
            let newBar = bar + 1;
            props.handleBarChange(newBar); // bad, which isn't surprising
            return newBar;
        });
    };

    return <div onClick={handleClick}>click me</div>;
};

If you fire a side effect such as calling something that sets state in a higher component from a useState updater function, you get the error "Cannot update a component from inside the function body of a different component" (but not always! It seems to depend on internal timing). This definitely seems like a bad idea when you look at it, but I couldn't find any mention in the docs that this is bad.

https://reactjs.org/docs/hooks-reference.html#functional-updates

There is the note about side effects generally on useEffect:

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase)

But this is not in the main body of a function component, doesn't feel like a true side effect as it's still just setting state within React, and doesn't feel like it's in the render phase either.

I initially wanted to comment about this here (https://github.com/facebook/react/issues/18178), because the general message of that thread was "don't set state of another component in a render method", and I've managed to get this error message without doing that, but the thread is locked. Thanks.

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

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

はじめの一歩

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

調査の方向性

リンクされたHooksリファレンスページ、特に関数型更新のセクションから始め、そこにあるガイダンスを、引用されているuseEffectの副作用に関する注記と比較してください。useStateのupdater内の副作用がサポートされていないのかを明確にし、関連する動作を説明してください。ドキュメントがこの例を曖昧さなく扱えば完了です。

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

評価

技術スタック
javascript, react
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

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

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