sir-haver
sir-haver

Reputation: 3592

Returning a function in useEffect

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?

Upvotes: 3

Views: 7974

Answers (2)

Reut
Reut

Reputation: 27

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.

Upvotes: 1

Ross
Ross

Reputation: 466

Per the React docs - If your effect returns a function, React will run it when it is time to clean up. https://reactjs.org/docs/hooks-effect.html. The returned function will fire when the component unmounts.

Upvotes: 3

Related Questions