
Data fetching in React.js / Next.js
Requirements
- React.js (16.8 or newer)
- Or Next (9.3.0 or newer)
useEffect
Use the hook to perform the data fetching in an effect, and store the results in a state variable.
import { useEffect, useState, useRef } from 'react'; function MyComponent() { const [data, setData] = useState(null); const isMounted = useRef(true); useEffect(() => { async function fetchData() { const response = await fetch('/my-data'); const data = await response.json(); if (isMounted.current) { setData(data); } } fetchData(); return () => { isMounted.current = false; }; }, []); if (data === null) { return 'Loading...'; } return <div>{data}</div>; }
SWR
SWR is a React Hooks library for data fetching that allows you to easily add server-side rendering (SSR) to your application. It works by returning a "stale" version of the data while a "revalidation" is being performed in the background. This allows your application to stay responsive while the data is being updated.
Example in a Nextjs application:
import useSWR from 'swr' function MyComponent() { const { data, error } = useSWR('/api/my-endpoint') if (error) return <p>Error loading data</p> if (!data) return <p>Loading...</p> return <div>{data.someData}</div> }
React Query
React Query is also a library for data fetching in React that allows you to easily add server-side rendering (SSR) to your application. It provides a simple and easy-to-use interface for fetching data, as well as a variety of advanced features for customizing the behavior of your queries.
Here is an example in a React component:
import { useQuery } from 'react-query' function MyComponent() { const { data, error } = useQuery('my-key', () => fetch('/api/my-endpoint')) if (error) return <p>Error loading data</p> if (!data) return <p>Loading...</p> return <div>{data.someData}</div> }
React Query allows you to choose from a variety of fetching strategies, including "refetch", "poll", and "cache-and-fetch". This means that you can customize the behavior of React Query more finely than you can with SWR.
TLDR
With useEffect alone you can fetch asynchronous data, but with libraries like SWR and React Query you have more options built in. SWR is generally easier to learn and use, but React Query provides more options for advanced scenarios.
Additional Resources
Related Posts
- Data fetching in React.js / Next.js2023-01-08
- What is React Hooks2021-08-25
- How to make a scroll to the top button in React2021-01-16