Returning a function in useEffect

Viewed 1015

I'm trying to understand why returning a function inside useEffect hook executes during the second time. For example:

const App = (props) => {
  const [change, setChange] = useState(false);

  useEffect(() => {
    return () => console.log("CHANGED!");
  }, [change]);

  return (
    <div>
      <button onClick={() => setChange(true)}>CLICK</button>
    </div>
  );
};

The first time the component renders, 'CHANGED' is not being logged, but after I click the button, it does. Does anyone know why?

2 Answers

If you use console.log() inside of useEffect but not in the return block, then it will be executed AFTER rendering. Putting it into return block means, you want use it as a clean-up function, so it'll be executed before the component unmounts or right before the next scheduled effect's execution. However, in your case, for the very first time, you neither have a scheduled effect nor something mounted. That's why you see the string "CHANGED" only when you click on the button.

Related