1×
Become a member
to unlock all features

Level Up!

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

Autoplay

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

    reactReact

    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(() => {
        console.log(props.id)
        fetch("https://swapi.co/api/people/"+props.id)
          .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.