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');
};
}, []);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With