loading...

Fetch Data with React.useEffect()

chantastic profile image Michael Chan ・1 min read

Things happen outside of React.
It's just a fact of life.

React gives us a single function for connecting to all of the events and effects that React doesn't automatically manage.

It's named React.useEffect() and you invoke it with a function.

React.useEffect(() => {
  // doStuff();
})

One of the things we use this function for is fetching data.

React.useEffect(() => {
  fetchPokemon(1);
})

This function will fire every single time the component is rendered.
That includes re-renders by React.useState.

In our Pokemon app, our "Next" button calls setPokemon(), re-rendering and re-running our React.useEffect() function.

function App() {
  let [index, setIndex] = React.useState(0);
  let pokemon = collection[index];

  return (
    <div>
      <button type="button" onClick={() => setIndex(index + 1)}>
        Next
      </button>

      ...
    </div>
  )
}

Give it a try

Use the Code Sandbox below to give this lesson a try directly in the browser.

Assignment

  1. Call the React.useEffect() function in the App component
  2. Give React.useEffect a function that calls fetchPokemon(index) for data
  3. Chain a .then() onto fetchPokemon(index) that logs out the returned json

Follow the 🧵 on Twitter:

Subscribe on YouTube:

Discussion

pic
Editor guide