Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Caching Data with React Query and Hooks
Next article icon

Data Fetching Libraries and React Hooks

Last Updated : 23 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Data fetching libraries like React Query and React Hooks simplify how developers fetch and manage data in React applications. These tools provide easy-to-use functions like 'useQuery' and 'SWR' that streamline API interactions and state management, improving code readability and reducing boilerplate.

By using the below libraries, we can create more efficient and responsive user interfaces while handling asynchronous data operations with ease.

Table of Content

  • Using built-in Fetch API
  • Using Axios
  • Using React Query
  • Using SWR
  • Using GraphQL API

Prerequisites:

  • GraphQL
  • React
  • React-hooks

Steps to Setup the React Project

Step 1: Create a reactJS application by using this command

npx create-react-app my-app

Step 2: Navigate to the project directory

cd marketplace

Step 3: Install Tailwind CSS

npm install -D tailwindcss
npx tailwindcss init

Step 4: Install the necessary packages/libraries in your project using the following commands.

npm install axios

Project Structure:

Screenshot-2024-03-20-120035

The updated dependencies in package.json file will look like:

 "dependencies": {
"@apollo/client": "^3.9.6",
"axios": "^1.6.7",
"graphql": "^16.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-markdown": "^9.0.1",
"react-query": "^3.39.3",
"remark-gfm": "^4.0.0",
"swr": "^2.2.5"
}
}

1. Using built-in Fetch API

For data fetching in React using the built-in Fetch API approach, you can use the 'fetch' function to make HTTP requests and handle responses asynchronously. You can manage the fetched data using React hooks such as `useState` to store data and loading states, and useEffect' to perform side effects like fetching data when the component mounts or updates.

Example: This example shows data fetching using built-in Fetch API.

JavaScript
// App.jsx  import { useEffect, useState } from "react"; import FetchPract from "./components/FetchPract";   export default function App() {      return (         <div>             <div>                 <h1>API Examples</h1>             </div>             <div>                 <FetchPract />             </div>         </div>     ) } 
JavaScript
// FetchPract.jsx  import { useEffect, useState } from "react";  export default function FetchPract() {     const [data, setData] = useState();     const [loading, setLoading] = useState(true);      useEffect(() => {         async function fetchData() {             try {                 const response = await fetch( 'https://api.github.com/repos/tannerlinsley/react-query');                 const jsonData = await response.json();                 setData(jsonData);             } catch (error) {                 console.log(error);             } finally {                 setLoading(false);             }         }          fetchData();     }, []);      if (loading) {         return <div>Loading...</div>;     }      return (         <div>             <h1>{data.name}</h1>             <p>{data.description}</p>             <strong>? {data.subscribers_count}</strong>{' '}             <strong>✨ {data.stargazers_count}</strong>{' '}             <strong>? {data.forks_count}</strong>         </div>     ); } 

Output:

Screenshot-2024-03-18-111913

2. Using Axios

For data fetching in React using Axios, you can utilize the Axios library to make HTTP requests easily. Axios provides a simpler and more streamlined syntax compared to the native Fetch API, making it popular for handling data fetching and handling responses in React applications.

Installation command:

npm install axios

Example: This example shows data fetching using axios library.Use you own API to test in place of url.

JavaScript
// App.jsx  import { useEffect, useState } from "react"; import Practice from "./components/Practice";  export default function App() {      return (         <div className="m-2">             <div className="p-2 font-semibold                              text-xl bg-slate-100 p-2                              text-center max-w-xs                              rounded-md m-2 mx-auto">                 <h1>API Examples</h1>             </div>             <div>                 <Practice />             </div>         </div>     ) } 
JavaScript
// components/Practice.jsx  import React, { useState, useEffect } from 'react'; import axios from 'axios'; import Markdown from 'react-markdown'; import remarkGfm from 'remark-gfm';  export default function Practice() {     const [data, setData] = useState([]);     const [loading, setLoading] = useState(true);      const options = {         method: 'GET',         url: 'your url',         headers: {             'X-RapidAPI-Key': 'Your rapidapi key',             'X-RapidAPI-Host': 'your host name'         }     };      useEffect(() => {         async function getData() {             try {                 const response = await axios.request(options);                 console.log(response.data.properties.description);                 setData(response.data.properties.description[0]);             } catch (error) {                 console.error(error);             } finally {                 setLoading(false);             }         }          getData();     }, []);      if (loading) {         return         <p className='font-semibold                        flex flex-col text-center                        min-h-screen justify-center'>             Loading...         </p>;     }      function renderData() {         return <p>{data}</p>     }      return data && renderData(); } 

Output:

gfg_fetch_axios
axios


3. Using React Query

Data Fetching Libraries like React Query simplify API data fetching in React apps. Using React Hooks such as 'useQuery' , they offer a powerful and intuitive way for developers to manage asynchronous data fetching, caching, and state management, enhancing the performance and user experience of applications.

Install React Query:

npm install react-query

Example: This example shows data fetching using React Query.

JavaScript
// components/QueryPract.jsx  import { QueryClient, QueryClientProvider, useQuery } from 'react-query';  export default function QueryPract() {     const { isLoading, error, data } =         useQuery('user', () =>             fetch( 'https://api.github.com/repos/tannerlinsley/react-query').then(res =>                 res.json()             )         )      if (isLoading) return <div>Loading...</div>      if (error) return <div>Error</div>      return (         <div>             <h1>{data.name}</h1>             <p>{data.description}</p>             <strong>? {data.subscribers_count}</strong>{' '}             <strong>✨ {data.stargazers_count}</strong>{' '}             <strong>? {data.forks_count}</strong>         </div>     ) } 
JavaScript
// App.jsx  import { useEffect, useState } from "react"; import QueryPract from "./components/QueryPract"; import { QueryClient, QueryClientProvider, useQuery } from 'react-query';  const queryClient = new QueryClient();  export default function App() {      return (         <div className="m-2">             <div className="p-2 font-semibold                              text-xl bg-slate-100 p-2                              text-center max-w-xs                              rounded-md m-2 mx-auto">                 <h1>API Examples</h1>             </div>             <div>                 <QueryClientProvider client={queryClient}>                     <QueryPract />                 </QueryClientProvider>             </div>         </div>     ) } 

Output:

Screenshot-2024-03-20-114108

4. Using SWR

SWR is a data fetching library that simplifies asynchronous data fetching in React apps. It leverages React Hooks like `useSWR` for efficient data caching, revalidation, and state management, improving performance and user experience.

Install SWR:

npm install swr

Example: This example shows data fetching using SWR.

JavaScript
// components/SwrPract.jsx  import useSWR from "swr";  const fetcher = (url) => fetch(url).then((res) => {     console.log("Fetched...")     return res.json(); });  export default function SwrPract() {     const { data, error, isLoading } = useSWR( "https://api.github.com/repos/vercel/swr",         fetcher,         { revalidateOnReconnect: true }     );      if (error) return <div>Error</div>     if (isLoading) return <div>Loading...</div>      return (         <div>             <h1>{data.name}</h1>             <p>{data.description}</p>             <strong>? {data.subscribers_count}</strong>{" "}             <strong>✨ {data.stargazers_count}</strong>{" "}             <strong>? {data.forks_count}</strong>         </div>     ); } 
JavaScript
// App.jsx  import { useEffect, useState } from "react"; import SwrPract from "./components/SwrPract";   export default function App() {      return (         <div className="m-2">             <div className="p-2 font-semibold                              text-xl bg-slate-100 p-2                              text-center max-w-xs                              rounded-md m-2 mx-auto">                 <h1>API Examples</h1>             </div>             <div>                 <SwrPract />              </div>         </div>     ) } 

Output:

Screenshot-2024-03-20-114531

5. Using GraphQL API

GraphQL APIs offer efficient data fetching with precise queries and real-time updates through subscriptions, enhancing development speed and user experience in modern web applications.

Install GraphQL:

npm install @apollo/client graphql

Example: This example shows data fetching using GraphQL.

JavaScript
// components/GraphPract.jsx  import React from 'react'; import { useQuery, gql } from '@apollo/client';  const GET_DATA = gql`       query Publication {         publication(host: "webdevelopement.hashnode.dev") {           isTeam           title           posts (first:10){             edges {               node {                 title                 brief                 url               }             }           }         }       } `;  const DataFetchingComponent = () => {     const { loading, error, data } = useQuery(GET_DATA);     if (data) {         console.log(data);         console.log(data.publication.posts.edges);     }     if (loading)         return <div>Loading...</div>;     if (error)         return <div>Error fetching data</div>;      return (         <div className='w-full md:max-w-lg                          mx-auto m-2 rounded-md'>             {                 data.publication.posts.edges.map((item, index) => {                     return (                         <div key={index}                              className='bg-gray-100 my-2 px-4 py-2'>                             <p className='text-xl font-semibold'>                                 {item.node.title}                             </p>                             <p >{item.node.brief}</p>                         </div>                     )                 })             }         </div>     ); };  export default DataFetchingComponent; 
JavaScript
// App.jsx  import { useEffect, useState } from "react"; import { ApolloProvider } from '@apollo/client'; import { ApolloClient, InMemoryCache } from '@apollo/client';    const client = new ApolloClient({     uri: 'https://gql.hashnode.com',     cache: new InMemoryCache(), });   export default function App() {      return (         <div className="m-2">             <div className="p-2 font-semibold                              text-xl bg-slate-100 p-2                              text-center max-w-xs                              rounded-md m-2 mx-auto">                 <h1>API Examples</h1>             </div>             <div>                 <ApolloProvider client={client}>                     <GraphPract />                 </ApolloProvider>             </div>         </div>     ) } 

Output:

gfg_fetch_1
graphQL



Next Article
Caching Data with React Query and Hooks

A

apj752003
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

  • Common libraries/tools for data fetching in React Redux
    In Redux, managing asynchronous data fetching is a common requirement, whether it's fetching data from an API, reading from a database, or performing other asynchronous operations. In this article, we'll explore some common libraries and tools used for data fetching in Redux applications. Table of C
    3 min read
  • Caching Data with React Query and Hooks
    If you have integrated Apis in your React js website, then you know that whenever a page is refreshed the data is re-fetched every time whether you have used useEffect to fetch data on the component mount or used some custom functions to fetch data. This results in unnecessary requests and decreased
    11 min read
  • How to Fetch Data From an API in ReactJS?
    ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, we’ll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
    5 min read
  • Building Custom Hooks Library in React
    Custom hooks in React allow developers to encapsulate and reuse logic, making it easier to manage state and side effects across multiple components. As applications become complex, developers often repeat similar patterns for state management, API calls, or event handling. This can lead to code dupl
    4 min read
  • Additional Built-in Hooks in React
    Hooks are functions that allow you to "hook" into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes. We will discuss the various
    6 min read
  • Context Hooks in React
    Context Hooks are a feature in React that allows components to consume context values using hooks. Before Hooks, consuming context required wrapping components in Consumer or using a Higher Order Component (HOC). Context Hooks streamline this process by providing a more intuitive and concise way to
    3 min read
  • Fetching Data from an API with useEffect and useState Hook
    In modern web development, integrating APIs to fetch data is a common task. In React applications, the useEffect and useState hooks provide powerful tools for managing asynchronous data fetching. Combining these hooks enables fetching data from APIs efficiently. This article explores how to effectiv
    4 min read
  • ReactJS Integrating with Other Libraries
    Integrating React JS with other libraries is a common practice in web development to utilize the functionality of those libraries. React JS is itself a JavaScript library. ReactJS workflow is like first importing the thing or component and then using it in your code, you can export your components a
    2 min read
  • 7 Best React Component Libraries in 2024
    React's dominance as a web development framework continues to surge in 2024. A significant factor behind this growth is the vast ecosystem of React component libraries. These pre-built UI components offer a powerful and efficient way to construct user interfaces for web, desktop, and hybrid applicat
    11 min read
  • Effect Hooks in React
    Effect Hooks in React allow components to interact with and stay synchronized with external systems, such as handling network requests, manipulating the browser's DOM, managing animations, integrating with widgets from other UI libraries, and working with non-React code. Essentially, effects help co
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences