Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Perform Asynchronous Actions (like fetching http data) in React with useEffect


    Whenever doing a side effect (like fetching data) in React, we can use the useEffect hook to perform that action and then set state afterwards.

    So we'll fetch some data inside of useEffect like this:

      useEffect(() => {
          .then(response => response.json())
          .then(result => setData(result))
      }, [props.id])

    Caution! make sure to set the dependency array (the second argument to useEffect) to contain any data that you use inside of the useEffect. Otherwise you could end up with an infinite loop as the useEffect will run every time the component in re-rendered.