Fetching data is a fundamental task in modern web or any kind of applications, as almost every web app interacts with an API or a backend service. There are several ways to fetch data in React, and choosing the right approach depends on factors like performance, reactivity, and ease of use. In this blog, we'll explore different major techniques and methods of fetching data in React.js.
Simple Fetch Method
The fetch() API in JS is used to request to the server and load the information in the webpages. You can call any API which returns data in JSON or XML. This method returns a promise.
export default function TextAPI() {
useEffect(() => {
fetch("https://example.com")
.then((response) => response.json())
.then((json) => console.log(json));
}, []);
return <div>HELLO WORLD!</div>;
}
Axios
For many developers, it is the preferred way of fetching data. Axios is a popular 3rd-party that simplifies HTTP requests with features like request cancellation, automatic JSON parsing, and better error handling.
import { useEffect, useState } from "react";
export default function FetchComponent() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => {
setData(json);
setLoading(false);
})
.catch((error) => console.error("Error fetching data:", error));
}, []);
if (loading) return <p>Loading...</p>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Many developers like this, but I don't. It is just a personal opinion. If we want to store data for caching, we'll need a new third party library, and this way, we will have to install several third party packages just for getting data from API? Doesn't make sense to me.
React Query
This one is my personal favorite. With this, we can achieve a lot more than just fetching data. It provide support for caching, prefetching, refetching, error handling, which improves overall user experience by preventing irregularities and ensuring our app feels really faster.
import { useQuery } from "react-query";
import axios from "axios";
const fetchPosts = async () => {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return data;
};
export default function ReactQueryComponent() {
const { data, error, isLoading } = useQuery("posts", fetchPosts);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Here, we can do a lot much things with a single library, we don't have to rely on multiple libraries for data handling. That's why a ❤ to React Query.
Server-Side Fetching with Next.js
In Nextjs, we can fetch data on server side, in server components. And that is much easier than the traditional useEffect way in React.
"use server";
export async function getServerSideProps() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await res.json();
return { props: { data } };
}
Now you can import and call this function anywhere in your Nextjs Application. In Server components you can call it directly without any issue, but in Client Components, You'll have to call it useEffect.
The best approach will be to fetch data in a parent server component, and pass that data to our client components.
Conclusion
There are various ways to fetch data in React, each with its own advantages and use cases. Choosing the right method depends on your project requirements, API structure, and performance needs. Happy coding! But my suggestion will be React Query, as it has a ton of features.
If you need guidance or a separate blog on any of the above methods, please let me know in comments. Checkout my blog: https://www.codepanda.online/