useRef does not persist value when used with createRoot
See original GitHub issueDo you want to request a feature or report a bug?
Report a bug.
What is the current behavior?
React.useRef
does not persist value when using with ReactDOM.createRoot
. It renders child component of main app component twice and does not persist ref value between these renders.
When we use React.useRef
with ReactDOM.render
it renders child component of main app component only once.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.
https://codepen.io/sudesh955/pen/zYYzdrg?editors=1011
What is the expected behavior?
It should persist ref across renders. For more details see comments in codepen link.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
version 0.0.0-experimental-f6b8d31a7
on chrome Version 78.0.3904.70 (Official Build) (64-bit) on ubuntu.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:9 (2 by maintainers)
I’m not sure I’m following why your conclusion is that this is a bug in React.
Can you explain the behavior you’re expecting? Conceptually,
StrictMode
intentionally completely “throws away” everything from one of the render attempts. That does include refs, by design. Rendering should not be making side effects, so throwing away the ref values during one of the renders should be completely safe. This would only affect the logic if you’re doing something else — for example, subscribing to a store — which you should not do while rendering because rendering should not have side effects. This is exactly whatStrictMode
is supposed to catch.Does this explanation help?
@probablyup yep, this is causing a myriad of issues in my library now as well. It seems that the state in
useRef
is not being persisted properly between renders and its causing component cleanup and no-op issues because of that (certain flags set inuseRef
’s state are not being maintained).People have opened up 2 issues related to this in the past couple days. It took me a while to figure out that CRA uses React.StrictMode by default, so many people are now running into this issue. Would appreciate some feedback about this and how it can be resolved.