Today I learned

Data fetching in React 18

Edit this Post Opens in new tab

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(() => {
    .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? Opens in new tab

Here are the key takeaways from his post:

  • Running effects twice shouldn't break your code. You should always ignore stale responses. If it does break your code, you have race conditions to fix. One way to do this, is to implement a cleanup function. This article offers a great explanation on how to do this: react docs: fetching data Opens in new tab
  • If you can, switch to server-side data fetching. Next.js and Remix both offer built-in solutions to deal with that, which are better suited than client-side data fetching in effects. If a server-side framework isn't an option, consider using a client-side cache like React Query Opens in new tab to fetch data.

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 on Twitter Opens in new tab or via Email Opens in new tab.

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