Confused by the useEffect cleanup behaviour

Viewed 35

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>
  );
};
1 Answers

How does the useEffect hook's clean up function only contains the previous state?

Because the effect captures the value of incrementTrigger when it's called.

The cleanup function the effect function returns has captured the same value.

Related