You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Bug: Derived value does not update in StrictMode #18003
When StrictMode triggers different behavior, it's usually a sign of a side effect or an unsafe pattern that maybe just happens to work in most cases.
What went wrong here?
StrictMode intentionally tests for this by double-invoking render methods. This means that, in DEV mode, React will render a component once- throw away any state updates- and then render again. (Regardless of how many times a component is rendered, the observable behavior should be the same unless there are side effects.)
In this particular case, mutating a ref during render is the side effect. The way this plays out in practice is like so:
"loose" input changes e.g. 1 -> 2
"strict" input renders for the first time
It changes prevValue ref from 1 -> 2 (side effect) and also updates state setInternalValue("")
It immediately re-renders with the newer state value (internalValue 1 -> 2)
React resets component state (including the update setInternalValue("")) in preparation for the second render. (Remember, StrictMode renders twice.)
"strict" input renders for the second time
Since the ref was mutated during the first render, it's already the same as the "new" prop so the code you expect to update the internalValue state doesn't get called.
How can you fix it?
The "quick fix" here would be to get rid of the render-phase side effect by moving your ref update to an effect:
if(prevValue.current!==value&&internalValue!==""){setInternalValue("");}useEffect(()=>{// It's safe to update your prev-value ref hereprevValue.current=value;});
It might not be obvious why this matters. After all- if React didn't double-render the component, it wouldn't break. That's why using the production bundle "fixes" things.
The truth is that side effects like this might cause things to break even outside of strict mode. The upcoming "concurrent" rendering mode is one such case, but it's not the only one. A component might render twice between commits even in "legacy" (synchronous) rendering mode in the event of an error. (In that case, React would bubble the error up to the nearest error boundary, then re-render before committing.)
Reacted by Kent C. Dodds, Mike Bifulco, Pablo Sáez, Nicolas Stepien, Snake, Aman Mahajan, Nicolas DUBIEN, albertobisello, kdragon, itsMapleLeaf and 3 more
@bvaughn in my question if you rendered it without strict mode, you would see Paul on screen. If you rendered it with strict mode, you'd see Nick. We thought this was due to using firstRender external variable. firstRender gets modified during first render, and on next strict render, it has different value, hence the second time timeout doesn't fire- and always Nick is printed. Do you agree with this?
If yes, then I found out that by replacing firstRender with a ref, even in strict mode, the output would be now the expected Paul. user ray suggested this could be because unlike firstRender variable, the ref was reinitialized on the second strict render. Hence on the second render the timeout was trigerred. Do you agree with this?
But if you could answer more precisely, whether you agree with the explanation (which I summarized in previous comment) user ray came up with, would be nice.
Because like I said we had the impression during second strict render the ref value from previous render was discarded. But in this thread it seemed you claimed ref value was retained on second strict render, and that contradiction confused me.
React renders twice in strict mode, without resetting anything
Hm before you said
This means that, in DEV mode, React will render a component once- throw away any state updates- and then render again
Isn't throw away and resetting kind of similar? I thought it could throw away a ref too.
Ps I think you are suggesting in the example of this thread there was update, in my question it was mount.
I think this is going to be my last response. I don't think this conversation is super helpful, since you seem to be ignoring the fact that the example code you posted has side-effects and so is known/expected to be broken. (This is the purpose of StrictMode double rendering, as the link I shared above explains.)
Isn't throw away and resetting kind of similar? I thought it could throw away a ref too.
Refs are mutable values. React initializes them once and then returns the same object/wrapper every time your component renders (including strict mode).
@bvaughn Well thanks for the effort anyway. I don't want to sound rude but I also have a feeling you didn't try to understand some of my comments above.
I'm sorry you feel that that way, but I answered your question in my comment above (#18003 (comment)) when I said that if your component is mounting, React will reset the ref between regular and strict mode render. That's why you see a different behavior than your code that modifies a local variable (which is not managed by React and so is only true for the initial render).
That being said, the reason I said this is not a very useful discussion is because the code pattern you're demonstrating is known to be broken and our documentation explicitly recommends against it (for reasons like the one we've been discussing).
Activity
nstepien commentedon Feb 9, 2020
FWIW it works fine with the production build of react-dom, change the import in codesandbox to test it:
bvaughn commentedon Feb 9, 2020
When
StrictModetriggers different behavior, it's usually a sign of a side effect or an unsafe pattern that maybe just happens to work in most cases.What went wrong here?
StrictModeintentionally tests for this by double-invoking render methods. This means that, in DEV mode, React will render a component once- throw away any state updates- and then render again. (Regardless of how many times a component is rendered, the observable behavior should be the same unless there are side effects.)In this particular case, mutating a ref during render is the side effect. The way this plays out in practice is like so:
prevValueref from 1 -> 2 (side effect) and also updates statesetInternalValue("")internalValue1 -> 2)setInternalValue("")) in preparation for the second render. (Remember,StrictModerenders twice.)internalValuestate doesn't get called.How can you fix it?
The "quick fix" here would be to get rid of the render-phase side effect by moving your ref update to an effect:
However, this Code Sandbox also looks like one of the derived state anti-patterns described in a blog post a while back. Maybe worth re-considering the higher level approach being used here and possibly going with a fully-controlled component instead?
Why does this matter?
It might not be obvious why this matters. After all- if React didn't double-render the component, it wouldn't break. That's why using the production bundle "fixes" things.
The truth is that side effects like this might cause things to break even outside of strict mode. The upcoming "concurrent" rendering mode is one such case, but it's not the only one. A component might render twice between commits even in "legacy" (synchronous) rendering mode in the event of an error. (In that case, React would bubble the error up to the nearest error boundary, then re-render before committing.)
amanmahajan7 commentedon Feb 10, 2020
Thank you @bvaughn for the quick reply and detailed explanation.
gmoniava commentedon Oct 12, 2021
@bvaughn when react renders second time intentionally due to strict mode, does it keep the value of
reffrom previous render, is that what you say? I had a similar situation: https://stackoverflow.com/questions/69393312/state-is-not-updated-in-strictmode, and I thought on second render react discarded therefvalue too (hence when I usedrefin my question instead of external variable, it seemed to work).bvaughn commentedon Oct 12, 2021
Ref isn't changed between regular and strict renders. Shouldn't matter.
Your example code has a side effect (
setTimeout) which should not happen in render. Move this to an effect.gmoniava commentedon Oct 12, 2021
@bvaughn in my question if you rendered it without strict mode, you would see
Paulon screen. If you rendered it with strict mode, you'd seeNick. We thought this was due to usingfirstRenderexternal variable.firstRendergets modified during first render, and on next strict render, it has different value, hence the second time timeout doesn't fire- and alwaysNickis printed. Do you agree with this?If yes, then I found out that by replacing
firstRenderwith aref, even in strict mode, the output would be now the expectedPaul. user ray suggested this could be because unlikefirstRendervariable, therefwas reinitialized on the second strict render. Hence on the second render the timeout was trigerred. Do you agree with this?Check the answer and comments.
bvaughn commentedon Oct 12, 2021
Reading or writing from external values during render is a side effect and is not supported in React components for reasons explained here:
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
gmoniava commentedon Oct 12, 2021
@bvaughn That's a general guideline, I see.
But if you could answer more precisely, whether you agree with the explanation (which I summarized in previous comment) user ray came up with, would be nice.
Because like I said we had the impression during second strict render the
refvalue from previous render was discarded. But in this thread it seemed you claimedrefvalue was retained on second strict render, and that contradiction confused me.bvaughn commentedon Oct 12, 2021
React renders twice in strict mode, without resetting anything:
https://github.com/facebook/react/blob/1e247ff892985488c6bcb87e924d7881f5c37261/packages/react-reconciler/src/ReactFiberBeginWork.new.js#L971-L1000
If it's an update,
useRefwill do exactly the same thing:https://github.com/facebook/react/blob/1e247ff892985488c6bcb87e924d7881f5c37261/packages/react-reconciler/src/ReactFiberHooks.new.js#L1632-L1635
If it's a mount,
useRefwill be initialized twice (re-initialized before strict mode):https://github.com/facebook/react/blob/1e247ff892985488c6bcb87e924d7881f5c37261/packages/react-reconciler/src/ReactFiberHooks.new.js#L1560-L1630
But components should not have side effects during render, so this distinction shouldn't matter.
gmoniava commentedon Oct 12, 2021
bvaughn commentedon Oct 12, 2021
I think this is going to be my last response. I don't think this conversation is super helpful, since you seem to be ignoring the fact that the example code you posted has side-effects and so is known/expected to be broken. (This is the purpose of StrictMode double rendering, as the link I shared above explains.)
Refs are mutable values. React initializes them once and then returns the same object/wrapper every time your component renders (including strict mode).
gmoniava commentedon Oct 13, 2021
@bvaughn Well thanks for the effort anyway. I don't want to sound rude but I also have a feeling you didn't try to understand some of my comments above.
bvaughn commentedon Oct 13, 2021
I'm sorry you feel that that way, but I answered your question in my comment above (#18003 (comment)) when I said that if your component is mounting, React will reset the ref between regular and strict mode render. That's why you see a different behavior than your code that modifies a local variable (which is not managed by React and so is only true for the initial render).
That being said, the reason I said this is not a very useful discussion is because the code pattern you're demonstrating is known to be broken and our documentation explicitly recommends against it (for reasons like the one we've been discussing).