In this tutorial, we will cover modern data fetching in React using some of the most popular approaches such as fetch API, axios, SWR, and React Query. By the end of this guide, you will have a deep understanding of how to perform efficient data fetching in your React applications.
- Fetch API:
The Fetch API is a native browser API that allows us to make HTTP requests. To use the Fetch API in React, you can simply make use of the globalfetch
function.
Here is an example of how you can make a GET request using the Fetch API in React:
import React, { useEffect, useState } from 'react';
const App = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data: ', error));
}, []);
return (
<div>
{data ? (
<div>{data}</div>
) : (
<div>Loading...</div>
)}
</div>
);
}
export default App;
- Axios:
Axios is a popular library for making HTTP requests in JavaScript. It has many features such as interceptors, automatic JSON parsing, and error handling. To use Axios in React, you first need to install it by runningnpm install axios
.
Here is an example of how you can make a GET request using Axios in React:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const App = () => {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => setData(response.data))
.catch(error => console.error('Error fetching data: ', error));
}, []);
return (
<div>
{data ? (
<div>{data}</div>
) : (
<div>Loading...</div>
)}
</div>
);
}
export default App;
- SWR:
SWR is a React Hooks library for remote data fetching with caching and revalidation. It is built by the team behind Next.js and provides a simple and powerful way to fetch data in React applications.
Here is an example of how you can use SWR in React:
import React from 'react';
import useSWR from 'swr';
const fetcher = url => fetch(url).then(response => response.json());
const App = () => {
const { data, error } = useSWR('https://api.example.com/data', fetcher);
if (error) return <div>Error fetching data</div>;
if (!data) return <div>Loading...</div>;
return (
<div>{data}</div>
);
}
export default App;
- React Query:
React Query is another popular library for data fetching in React applications. It provides a set of hooks for fetching, caching, and updating data. React Query is highly customizable and comes with built-in features such as caching, error handling, and automatic refetching.
Here is an example of how you can use React Query in React:
import React from 'react';
import { useQuery } from 'react-query';
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
};
const App = () => {
const { data, isLoading, isError } = useQuery('data', fetchData);
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error fetching data</div>;
return (
<div>{data}</div>
);
}
export default App;
In this tutorial, we covered modern data fetching in React using the Fetch API, Axios, SWR, and React Query. Each of these approaches has its own strengths and use cases, so choose the one that best fits your needs. Experiment with these different methods and see which one works best for your React applications. Happy coding!
i've saw all the video but didn't get what the Modern way to data fecthing, it is query or cash itself ?
Man, you deserve way more views. It's unreal how much quality you put into your content. I've been following you since last year, and I really appreciate not just the knowledge you have, but also your ability to teach it—which are two different skills
I am going to join your course Project React! (Let me have some time n money ;))
این نیز بگذرد
"A Modern Data Fetching" , Really? you don't know this?
Now I use zustand to initiate data requests in useXXScore and the experience is very good.
In my next js project i use react query to fetch data. But i use server action to mutate the data into the server.
React query can easily handle pagination 😊
Thanks darius
react query or redux toolkit ? which is better
just use openapi-fetch and be done with it and its type safe
useQuery is so good. I just love using it. I'm even shocked that some companies still use fetch in their code as it always slows everything down.
Why can't we make more simple use of reducer function in one class for CRUD request insted of doing all this try catch
is there a text version of lessons included to follow along in your Project react course?? ( I hate watching endless watery videos although idk about your videos but still text version is a much more preferable and a quicker way to learn )
What about if did fetch my data in a JS file and than use it in another Jsx file ?
I love your videos! Please keep making more
Exceptional content and very clear!!! Loved the comparison among the possibilities to fetch the data. For people like me, that is still learning, it is a great way to undestand the differences, pros and cons! Congrats and thanks for sharing!
In the last example what if we want to fetch data for individual page parameters what should we have to do in that case
interesting, I always fetched like your third example, and cache the data then my components take what they need from the cache.
I will have a look to useQuery
3 and a half minutes in and i know this is gonna be about react query
I have a question that my app is about lms , i want to have SEO for the some page of it , but my ui lib is use MUI and just because i just need to SEO for some page do need to use nextjs now ?
In the last example, there is no need to use Suspense for loading. Because in production there is no loading, since that server component is rendered at build time