react icon indicating copy to clipboard operation
react copied to clipboard

Bug: Setting same state in useLayoutEffect triggers additional renders in React 18

Open timphillips opened this issue 3 years ago • 1 comments

I'm not sure if this is a bug or expected behaviour, but we've noticed this change while upgrading our project to React 18. Setting state in a useLayoutEffect in this particular scenario is causing additional renders in React 18 compared to React 17. The previous behaviour in React 17 seems like the correct, expected behaviour.

React version: 18.2.0

Steps To Reproduce

Given this component:

function App() {
  const [state, setState] = useState("loading");

  useLayoutEffect(() => {
    setState("loading");

    setTimeout(() => {
      setState("data");
    }, 10);
  }, []);

  console.log("Render with state:", state);

  return <div>{state}</div>;
}

Note that this is a contrived example to minimally demonstrate the issue; it ignores proper effect cleanup, etc.

Link to codesandbox: https://codesandbox.io/s/flamboyant-mendel-3gxysj?file=/src/index.js

The current behavior

React 18 logs this output:

Render with state: loading 
Render with state: data
Render with state: data

The expected behavior

React 17 logs this output:

Render with state: loading
Render with state: data

Notes:

  • It seems the call to setState("loading") is causing the extra render. Shouldn't this call have no effect since the state's initial value is already "loading"? If you change the state's initial value to something else (like undefined), then the output is what I'd expect:
Render with state: undefined
Render with state: loading 
Render with state: data 
  • useEffect produces the expected output in both React 17 and React 18.

timphillips avatar Oct 19 '22 14:10 timphillips

Hi @timphillips, I think this is a bug, I'll try to fix it. Thanks for report it!

damianpumar avatar Oct 24 '22 07:10 damianpumar

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

github-actions[bot] avatar Apr 09 '24 23:04 github-actions[bot]

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

github-actions[bot] avatar Apr 17 '24 10:04 github-actions[bot]