Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does cleanup functions work in JavaScript

I'm currently trying to learn React and in the process I came across a concept called debouncing. This was related to useEffect hook. The concept of debouncing I started to understand but what I cannot understand is how the cleanup functions work. To be more specific, I cannot understand how the return function in the useEffect is actually executed before all the code in the hook is.

  useEffect(() => {
    console.log('Before cleanup');

    return () => {
      console.log('Cleanup');
    };

  }, []);
like image 983
Adrian Avatar asked Jun 27 '26 02:06

Adrian


1 Answers

Cleanup function works when useEffect method is still running and there's an update in the useEffect dependency at the same time. This generally happens when you have an unresolved fetch in the useEffect method.

In that case, useEffect terminates the first process by executing return statement and begins processing the latest useEffect call.

In your code, this will not happen because the useEffect will always terminate almost immediately when its called. Try using wait(10000) and trigger the useEffect method during that waiting time.

like image 78
Zahit O. Avatar answered Jun 29 '26 16:06

Zahit O.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!