Getting Started with React - Lesson #18

Creating React Effects with useEffect()

When building React components, we may want to run some code on special occasions. The main times we would want to run extra code:

  • When the component is mounted (rendered to our app)
  • When the component is re-rendered
  • When the component is unmounted (removed from our app's view)

These are often called lifecycle events. They essentially boil down to:

  • When a component is created (mounted)
  • When a component is updated (re-rendered)
  • When a component is removed (unmounted)

In React, we have a React hook called useEffect that lets us handle all of the above.

In order to have some code run when a component is rendered for the first time, we will use useEffect.

jsx
import { useEffect } from 'react';

function App() {

    useEffect(() => {

        // run this code whenever our app is mounted
    
    }, []);

    return (
        <div>
            the effect only runs when the component is first mounted
        </div>
    );
}

This is a perfect place to run a fetch to get information from an API.

In order to run an effect whenever our component gets updated, we pass information into the second argument. Our effect will only run if React sees that something in this array has changed.

Let's say we have a component that displays the latest tweet from a user. We want to get the latest tweet inside of our effect. But we only want it to run if we see a different user.

jsx
import { useState, useEffect } from "react";

function UsersLatestTweet({ user }) {
  const [tweet, setTweet] = useState(null);

  useEffect(() => {

    // go get the latest tweet
    fetch(`http://twitter.com/api/${user.username}/tweets`)
      .then(res => res.json())
      .then(tweet => setTweet(tweet));

  }, [user]); // only run this effect if user changes

  // render the tweet
  return <div>{tweet.text}</div>
}

Sometimes we may want to run some cleanup code like removing an eventListener or unsubscribing from a stream.

We do this by returning a function inside of our useEffect.

jsx
import { useEffect } from "react";

function TweetStream() {
  useEffect(() => {
    tweetStream.subscribe();

    // unsubscribe from the tweet stream when this component is unmounted
    return () => {
      tweetStream.unsubscribe();
    }
  }, [])

  // ...
}

useEffect is powerful and effective when used in the right circumstances. It can take some time to wrap your head around using effects. For the most part, we will be using effects when our components are first mounted and when they are updated.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.