Data fetching in React 18

Edit this Post

#react#api

If you’ve worked with React you’ve possibly done something like this to fetch data from an API:

const [data, setData] = useState(null)

useEffect(() => {
  fetch('https://pokeapi.co/api/v2/pokemon')
    .then((res) => res.json())
    .then((data) => setData(data))
}, [])

With the release of React 18 a lot of people were wondering if this is still a good practice. The confusion stems from the fact that React 18 renders everything twice in strict mode in development.

In this react thread on the react subreddit, Dan Abramov, a member of the React core team at meta, shares a lot of valuable information on this topic:

What is the recommended way to load data for components in React 18?

Here are the key takeaways from his post:

A final note: these changes have nothing to do with the release of React 18. In fact, these issues have existing much longer. The react team just started documenting them now. The main issue here is, that we may have all used effects like useEffect wrong the whole time.

I’ve already wrote about that topic on other posts like my blog post the mistakes I made using React and my Today-I-learned post: missusing useEffect.

Now’s a great time to refactor and apply the changes mentioned above.


I hope you enjoyed this post and learned something new. If you have any questions, feel free to reach out to me via mail.

If you want to support me, you can buy me a coffee. I would be very happy about it!

Buy me a coffee

I wish you a wonderful day! Marco