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?
CodePudding user response:
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.
CodePudding user response:
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.