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

InstructorChris Achard

Share this video with your friends

Send Tweet

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))
  }, [])

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.