Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Sheraz Manzoor
Sheraz Manzoor

Posted on

     

Different Ways to fetch data in Reactjs

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.

exportdefaultfunctionTextAPI(){useEffect(()=>{fetch("https://example.com").then(response=>response.json()).then(json=>console.log(json))},[])return<div>HELLOWORLD!</div>}
Enter fullscreen modeExit fullscreen mode

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';exportdefaultfunctionFetchComponent(){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>;}
Enter fullscreen modeExit fullscreen mode

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';importaxiosfrom'axios';constfetchPosts=async()=>{const{data}=awaitaxios.get('https://jsonplaceholder.typicode.com/posts');returndata;};exportdefaultfunctionReactQueryComponent(){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>;}
Enter fullscreen modeExit fullscreen mode

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"exportasyncfunctiongetServerSideProps(){constres=awaitfetch('https://jsonplaceholder.typicode.com/posts');constdata=awaitres.json();return{props:{data}};}
Enter fullscreen modeExit fullscreen mode

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/

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Developer 💻 | Programmer 🧑‍💻 | MERN Stack Developer | Learner | Blogger
  • Location
    Pakistan
  • Education
    ICS Inter
  • Pronouns
    Sheraz Manzoor, MERN Stack developer, He, Blogger, Him
  • Work
    MERN Stack developer at infinitydevs.io
  • Joined

More fromSheraz Manzoor

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp