Search code examples
reactjsuse-effect

In React, what is the difference these useEffect?


  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?


Solution

  • 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]);