reactjs / reactjs/react.dev

Running an effect only on update vs Strict mode

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

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

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

説明

I have written a variation of the useEffect hook that should only run on updates. I used a useRef hook to accomplish this the way the FAQ in the old docs recommends it here:

image

I couldn't find the same piece in the new documentation.

The problem is that the effect still runs on the initial render when strict mode is on:
https://codesandbox.io/s/delicate-lake-88phjz?file=/src/App.js

however it behaves correctly when the strict mode is off:
https://codesandbox.io/s/hungry-wright-tl7p43?file=/src/App.js

In the former example the message is logged to the console right away even though it shouldn't be.

The possible explanations I can think of are:

  1. I'm doing something wrong. Can you please point the mistake out for me?
  2. The old docs are off and this is not the right way to do it. In this case can you please let me know what the right way of achieving this behavior is?
  3. The strict mode is to blame. I do find it irritating at times, if I'm frank, but that's probably unlikely.

Can someone help me with this? Thanks a lot!

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

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

はじめの一歩

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

調査の方向性

リンクされている2つの CodeSandbox の例で動作を再現することから始め、Strict Mode の場合と Strict Mode でない場合を比較してください。現在の useEffect と useRef のドキュメントを古い FAQ の抜粋と併せて読み、初回のレンダーをスキップするエフェクトについて推奨される動作が明確に文書化されるか、issue が Strict Mode で想定される動作として説明されれば完了です。

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

評価

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

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

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