0

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>
  );
};
  • What is a [Closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#closure) – Thomas Sep 06 '22 at 13:37
  • There is a single `incrementTrigger` variable that is shared, through a closure, by all the functions inside `TestComponent`. Also, please make sure your posts include a question, there's no `?` in your post or an explanation of actual versus expected behavior. See https://stackoverflow.com/help/how-to-ask – Ruan Mendes Sep 06 '22 at 13:41

1 Answers1

0

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.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • If this is the answer, this post should be closed as a duplicate. – Ruan Mendes Sep 06 '22 at 13:38
  • @JuanMendes A generic "How do closures work?" is likely not to tell OP much, though. – AKX Sep 06 '22 at 13:45
  • I think it will help more than just saying what you said above (which would make more sense as a comment). This is such a basic feature of JavaScript, we don't need another answer on StackOverflow. They need to understand the basic feature. If they have a real question after they at least read about closures, then they can ask a well posed question. – Ruan Mendes Sep 06 '22 at 13:57