Description
- Check if updating to the latest Preact version resolves the issue
Describe the bug
When using the useMemo hook to calculate a value and then using this value to conditionally update the state during render, the app indefinitely re-renders. Something like shown below
const [value, setValue] = useState(false);
const data = useMemo(() => {
return { data: 'some data' };
}, [value]);
const [prevData, setPreviousData] = useState(data);
if (prevData !== data) {
// This causes the infinite loop
setPreviousData(data);
}
Preact version - 10.21.0
To Reproduce
Sandbox - https://codesandbox.io/p/sandbox/usememo-behavior-preact-w3rlrv
Steps to reproduce the behavior:
- Go to the sandbox and open the console
- Click on the 'Set to true' button
- See error (and the console log of the memoized value changes)
After some debugging, it seems like the internalHookState of the useMemo hook is not updated with the new dependency args if a state update happens during the render cycle. And the hook always ends up comparing the dependency array with the very first dependency array. This is resulting in a recalculation of the hook every render and the component re-renders indefinitely.
Expected behavior
The useMemo hook should remember the last provided dependency array and should only recalculate the value when there is an actual change in the dependency array.
React seems to be handling this case as expected - https://codesandbox.io/p/sandbox/usememo-behavior-react-l3cxhs