reactjs / reactjs/react.dev

Running an effect only on update vs Strict mode

Open
#6,302 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the behavior in the two linked CodeSandbox examples, comparing the Strict Mode and non-Strict Mode cases. Read the current useEffect and useRef documentation alongside the old FAQ excerpt; done means the recommended behavior for effects that skip the initial render is clearly documented or the issue is explained as expected Strict Mode behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.