How to fetch data in React 18

Gotta fetch em all

Stephan Bakkelund Valois
5 min readJun 27, 2022
React 18 useEffect, different methods for fetching data in React 18

Did you recently upgrade to React 18, only to find out all your useEffects are running crazy?

Table of Contents

Example repo: https://github.com/sbvalois/react-18-fetch

Why?

The recent changes to React useEffect makes the hook run twice on mount. This may or may not be a problem, depending on what you’re using your useEffect for.

A very common pattern is to fetch initial data inside a useEffect:

const Component = () => {
const [data, setData] = useState([])
useEffect(() => {
fetchData().then(setData)
}, [])
}

This still works in React 18, however you will be hitting your server twice with this code, even though you’ve appended an empty dependency array.

The useEffect function was never ment to be used the way it’s been used for fetching data, but as a way to synchronize with external systems. User events should go into event handlers…

--

--