Skip to content

Bug: useRef acting weird in Strict mode. #20835

Closed
@charlie1404

Description

@charlie1404

React version: latest (tested with 16 and 17 both)

Steps To Reproduce

Please see attached videos for reference and code sandbox for the live experiment

  1. Set component in StrictMode but wrapping it in <React.StrictMode>
  2. Have a useRef in that component that takes an empty array as input.
  3. Try mutating it on every render, maybe something like refVar.current.push("doesn't really matter what goes in here")
  4. use that array (have made a simple list from that, but should apply to all cases)
  5. array is being mutated from a different universe (to me it seems that only 😅 ).

Link to code example:
https://codesandbox.io/s/strict-bug-mrv-w7r11

The current behavior

There are 2 console.log to show the value of the array before and after array mutation.
In strict mode when clicked provided button array gets an extra element, same as pushed valued. (Please see attachment one)

The expected behavior

I believe this should be the same as when not in not strict mode.

Apart from this I also have tried using the debugger to see what actually is happening. When added breakpoint to list.current.push() it seems dev tools is stopping on that line twice. What even more confusing to me is, if in case function ran(rendered) twice, how come there is console only once, please attached video (attachment two ) for the same.

Attachments:

  1. https://user-images.githubusercontent.com/20264337/108258484-12ce5300-7186-11eb-8bb2-6e82a14ac856.mov
  2. https://user-images.githubusercontent.com/20264337/108256943-1fea4280-7184-11eb-9840-2dfc243eb6ae.mov

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions