Skip to content

Bug: React 18 Strict mode does not simulate unsetting and re-setting DOM refs #24670

Open
@JMartinCollins

Description

@JMartinCollins

React version: 18.1.0

Steps To Reproduce

  1. Use <React.StrictMode>
  2. Set a ref to a JSX element in a component
  3. Create a useLayoutEffect/useEffect in the component where the returned cleanup function console logs the ref
  4. Save and refresh the app
  5. You should have access to the ref element in the the useLayoutEffect/useEffect cleanup function during the simulated unmount.

Link to code example: https://codesandbox.io/s/proud-snow-ox4ngx?file=/src/App.js

The current behavior

Does not unset/re-set refs in simulated unmount. This could lead to unexpected bugs in development like having double-set event listeners, i.e.if( ref.current ){ //add eventlistener to it }and might not match the behavior of actually unmounting the DOM node as described in the docs: https://reactjs.org/docs/strict-mode.html

On the second mount, React will restore the state from the first mount. This feature simulates user behavior such as a user tabbing away from a screen and back, ensuring that code will properly handle state restoration.

The expected behavior

In normal unmounts and mounts refs are unset(before layout effects are cleaned up) and set(before layout effects).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions