How the useEffect hook's clean up function only contains or works with the previous states. As we know the useEffect process including it's cleanup runs after a re-render.
Here in TestComponent, the "incrementTrigger" state used in cleanup function contains it's previous value.
const TestComponent= () => {
const [incrementTrigger, setIncrementTrigger] = useState(1);
const toggleHandler = () => {
setIncrementTrigger(incrementTrigger + 1);
};
useEffect(() => {
console.log("Component Updated " + incrementTrigger);
return () => {
console.log("Clean Up - " + incrementTrigger);
};
}, [incrementTrigger]);
return (
<div className="mainContainer">
<h2 className="text">
This is a temporary component to observe the behaviour of useEffect
hook.{" "}
</h2>
<button onClick={toggleHandler}>Toggle</button>
</div>
);
};