DEV Community

Kenneth Lum
Kenneth Lum

Posted on

The two general patterns of useEffect() in React Hooks

When we use useEffect(), there are two common patterns. Let's start with the easier one:

useEffect(() => {
  // do the set up

  return () => { 
    // do the take down
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Here, we are providing an empty dependency array at the end, so the provided function will only execute once. It is for "set up" and "take down".

Where it says // do the set up, it is to do the set up, such as fetching data, or getting some data from localStorage, or set up any setInterval() or setTimeout(). This is similar to componentDidMount back in the days of class components.

Then that function returns another function, and this function is to "take down" or "clean up". It is where // do the take down is up above. This is similar to componentWillUnmount in the class components.

So it is quite clear: one set up, one clean up.

The pattern above is to run once. The other pattern is to "run often".

It can be

useEffect(() => {
  // do the set up

  return () => { 
    // do the take down
  };
});
Enter fullscreen mode Exit fullscreen mode

or

useEffect(() => {
  // do the set up

  return () => { 
    // do the take down
  };
}, [friendID]);
Enter fullscreen mode Exit fullscreen mode

Note that the first form does not have the dependency array at all. This way, it is to run every time. Typically, it is to "take down" once, and to "set up" once, having a "small loop" between our grand "set up" and "take down". It is similar to what we do for componentDidUpdate.

The code below that is to run every time when friendID changes, and it is for example, to "take down" the subscription of whether the friend is online or not, and then subscribe to another friend's online status to see whether the friend is online or not. So we can view it as a tiny take down, and a tiny set up.

So that's basically it, two actions for componentDidMount and componentWillUnmount, and then the "tiny actions" or a tiny loop, each time for a componentDidUpdate.

And if we have to do something for the "grand" set up and take down, and then a "tiny loop", and the actions are quite different for them, then we can use two useEffect():

useEffect(() => {
  // do the set up

  return () => { 
    // do the take down
  };
}, []);

useEffect(() => {
  // do the set up

  return () => { 
    // do the take down
  };
}, [friendID]);
Enter fullscreen mode Exit fullscreen mode

so the first useEffect() is to run once, for the grand set up and take down, and the second one is for the "tiny loop".

Reference:

  1. https://reactjs.org/docs/hooks-effect.html (Official docs)
  2. https://reactjs.org/docs/hooks-overview.html
  3. https://wattenberger.com/blog/react-hooks by Amelia Wattenberger
  4. https://overreacted.io/a-complete-guide-to-useeffect/ by Dan Abramov

Top comments (1)

Collapse
 
aalphaindia profile image
Pawan Pawar

Good one!!