Closed
Description
State is not preverved across StrictMode re-mounts. If StrictMode is removed there is no bug.
React version: 18.2.0
Steps To Reproduce
- https://stackblitz.com/edit/react-strict-mode-cosrnr?file=index.js,index.html
- Click on the button, and look at the console. The
boolean
state in theuseSetStateWithoutUseEffect
hook is set totrue
(we have aconsole.log('setting boolean to true')
.
However it is instantly set back tofalse
, 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 hookuseSetStateWithoutUseEffect
, 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