In this section:
https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
const handleSubmit = useEventCallback(() => {
alert(text);
}, [text]);
Where useEventCallback is:
function useEventCallback(fn, dependencies) {
const ref = useRef(() => {
throw new Error('Cannot call an event handler while rendering.');
});
useLayoutEffect(() => {
ref.current = fn;
}, [fn, ...dependencies]);
return useCallback(() => {
const fn = ref.current;
return fn();
}, [ref]);
}
Which means useLayoutEffect() is re-run each time fn changes.
Since fn in the example is re-created on each render it means that useLayoutEffect() always re-runs.
But at the same time the fn function can't be not created on each render because it depends on text which is re-defined on each render.
In this section:
https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
Where
useEventCallbackis:Which means
useLayoutEffect()is re-run each timefnchanges.Since
fnin the example is re-created on each render it means thatuseLayoutEffect()always re-runs.But at the same time the
fnfunction can't be not created on each render because it depends ontextwhich is re-defined on each render.