Clean up function
There is like this code
useEffect(() => {
console.log('effect execute !!')
return () => {
console.log('in return function')
};
}, [something]);
this function of return is called clean up function
When does clean up function execute
- When component unmounts
- Just Before useEffect executes
Real life example
useEffect(() => {
document.addEventListener('keydown', handleKeyDown);
}, [something]);
If you write this code, keydown event adds every time when something changes. At the worst case, it causes a memory leak
so you should add clean up function, to remove event just before useEffect executes (= after state of something changes)
useEffect(() => {
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [something]);
Top comments (0)