useEffect(() => {
return () =>
setTimeout(() => set_current_focus(index_map[comp_index]), 1000);
}, [comp_index]);
and
useEffect(() => {
return setTimeout(() => set_current_focus(index_map[comp_index]), 1000);
}, [comp_index]);
Based on my testing, there is no difference.
Can someone confirm?
CodePudding user response:
In the first code example, you are returning a function from the callback function of the useEffect hook; this returned function is used as a cleanup function that is executed before the component unmounts as well as before running the useEffect hook again.
In the second code example, you are returning the result of calling setTimeout, i.e. the id of the timer that can be used to cancel the timer. This return value is not used by react, so it useless to return the result of setTimeout from the callback function of the useEffect hook.
CodePudding user response:
Both useEffect snippets are incorrect.
The value returned by the callback passed to useEffect should be a function used for cleaning up things (like clearing the timeout in your case).
So the correct usage looks like this:
useEffect(() => {
const timeout = setTimeout(
() => set_current_focus(index_map[comp_index]),
1000
);
return () => clearTimeout(timeout);
}, [comp_index]);
