Skip to content

Bug: state is not preverved across re-mounts in StrictMode  #25893

Closed
@barroudjo

Description

@barroudjo

State is not preverved across StrictMode re-mounts. If StrictMode is removed there is no bug.

React version: 18.2.0

Steps To Reproduce

  1. https://stackblitz.com/edit/react-strict-mode-cosrnr?file=index.js,index.html
  2. Click on the button, and look at the console. The boolean state in the useSetStateWithoutUseEffect hook is set to true(we have a console.log('setting boolean to true').
    However it is instantly set back to false, even though its setter is not called...
    I have no idea what causes this, but since it only happens in strict mode, and reflects a loss of state (and I can't for the life of me see any bug in the hook useSetStateWithoutUseEffect, as I think setting state conditionnally outside a useEffect or useCallback shouldn't be a problem), I can only assume it's a React bug.

Here is the hook code:

export const useSetStateWithoutUseEffect = (show) => {
  const previousShowRef = useRef();
  const [boolean, setBoolean] = useState(false);
  if (!previousShowRef.current && show) {
    setBoolean(true);
  }
  previousShowRef.current = show;
  return boolean;
};

Link to code example: https://stackblitz.com/edit/react-strict-mode-cosrnr?file=index.js,index.html

The current behavior

The value boolean is set to true as expected on the click, but then instantaneously set back to false, even though its setter is not called...

The expected behavior

The value boolean should be set to true upon clicking and stay that way. (which works in non-strict mode)

EDIT: simplified a LOT the code example

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions