React Hooks: useEffect()

danimal92 profile image Daniel Zaltsman ・2 min read

In my last post, I covered useState() and its usefulness in a functional component. In the same vein of imitating class component functionality, we have useEffect() to perform side effects in function components. In class components, we put side effects in componentDidMount and componentDidUpdate.

Here is a short example of useEffect():

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;

In useEffect() you have three parts: code that runs when useEffect() is called(which is on every render), the cleanup effect(runs when the component unmounts), and a parameter that you can pass into useEffect() which tells that useEffect() function to run only when that parameter changes. So if I put in a state variable, the effect may run when that variable changes. But if that component re-renders with the same value, it will not fire the effect.

In the example above, the effect will fire every time the component is re-rendered. However, if we placed the count as a second parameter and on a re-render it hadn't changed, the effect will not fire. The current example makes more sense since this is probably something you want to display at all times this component is mounted. You can even have multiple useEffect functions with these second parameters and separate your tasks based on what is being changed on a re-render.

Here's another example:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);

This is the useEffect with a second parameter placed in it. This will only fire if count changes.

Lastly, using the effect cleanup helps avoiding duplicating your code in componentDidUpdate and componentWillUnmount.

function FriendStatus(props) {
  // ...
  useEffect(() => {
    // ...
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);

The return statement is the cleanup: this effect runs when the component unmounts. In this case, it is unsubscribing from a friend's status.

Posted on by:

danimal92 profile

Daniel Zaltsman


Full stack developer with a passion for problem solving and creating products that are useful to the everyday consumer.


Editor guide