,

The Comprehensive Guide to Modern Data Fetching in React

Posted by


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.

  1. 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 global fetch 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;
  1. 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 running npm 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;
  1. 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;
  1. 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!

0 0 votes
Article Rating
39 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@iury664
2 months ago

i've saw all the video but didn't get what the Modern way to data fecthing, it is query or cash itself ?

@EyalCumartesii
2 months ago

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

@deepeshpakhare
2 months ago

I am going to join your course Project React! (Let me have some time n money ;))

@HoomaanHRG
2 months ago

این نیز بگذرد

@joshuagalit6936
2 months ago

"A Modern Data Fetching" , Really? you don't know this?

@ningshenbj
2 months ago

Now I use zustand to initiate data requests in useXXScore and the experience is very good.

@mDHARYL
2 months ago

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

@vramv9999
2 months ago

react query or redux toolkit ? which is better

@rogerramjet69
2 months ago

just use openapi-fetch and be done with it and its type safe

@tomasburian6550
2 months ago

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.

@viveksah2069
2 months ago

Why can't we make more simple use of reducer function in one class for CRUD request insted of doing all this try catch

@C0D3O
2 months ago

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 )

@songlyrics6612
2 months ago

What about if did fetch my data in a JS file and than use it in another Jsx file ?

@mikaborosh4190
2 months ago

I love your videos! Please keep making more

@jennifermagpantay7933
2 months ago

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!

@sahajranipa
2 months ago

In the last example what if we want to fetch data for individual page parameters what should we have to do in that case

@Mylordkaz
2 months ago

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

@begoing07
2 months ago

3 and a half minutes in and i know this is gonna be about react query

@minhnhatnguyen8200
2 months ago

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 ?

@tyafizi
2 months ago

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