Today I learned

Data fetching in React 18

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 React 18?

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.
  • 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 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 me may have all used effects like useEffect wrong the whole time.

I've already wrote about that topic on another Today-I-learned post: missusing useEffect.

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

Greetings Marco

Go back to other today-i-learned posts