Bug: useMemo hook executes twice
See original GitHub issueI’m using useMemo hook with an empty dependency array in a component withlazy + Suspense, so I expect the function inside useMemo will be called once, but sometimes the function is called twice.
No StrictMode, no rerenders.
useMemo(() => {
console.log('useMemo');
}, []);
React version: 18.2.0
I can’t reproduce it with version 17.0.2
Steps To Reproduce
Please, take a look at the simplified example. I could reproduce it on a regular basis after I’ve added setState call inside useMemo. As the issue is hard to reproduce, there is a script that reloads the page until the bug appears.
Link to code example: https://codesandbox.io/s/smoosh-forest-g6ft5o
Pay attention, that function in useEffect was called once, which is expected behavior, but useMemo was called twice.
In the real project, there is no setState call inside useMemo and no warnings, but anyway I meet the issue every 10-20 page reloads.
If I delete lazy it works as expected. If I drop LongComponent it works as expected.
The current behavior
The function passed to useMemo is executed twice despite the empty dependency array, and the component wasn’t rerendered.
console:
useMemo
useMemo
useEffect
The expected behavior
The function passed to useMemo is executed only once.
console:
useMemo
useEffect
Issue Analytics
- State:
- Created a year ago
- Reactions:3
- Comments:14 (2 by maintainers)
Top Related StackOverflow Question
Please check this https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily. You can manually save this instance to ref on very first render (or even lazily).
Yes, I see this is normal https://reactjs.org/docs/strict-mode.html