DEV Community

chantastic
chantastic

Posted on

Fetch Data with React.useEffect()

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();
})
Enter fullscreen mode Exit fullscreen mode

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

React.useEffect(() => {
  fetchPokemon(1);
})
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)