DEV Community

Kaziu
Kaziu

Posted on

What is "return" in useEffect

Clean up function

There is like this code

useEffect(() => {
  console.log('effect execute !!')
  return () => {
    console.log('in return function')
  };
}, [something]);
Enter fullscreen mode Exit fullscreen mode

this function of return is called clean up function

When does clean up function execute

  1. When component unmounts
  2. Just Before useEffect executes

Real life example

useEffect(() => {
  document.addEventListener('keydown', handleKeyDown);
}, [something]);
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)