React30-Project 17: Implementing React Query in a Web App
Introduction
In this tutorial, we’ll explore how to integrate React Query into a basic web app. React Query is a powerful library for managing, caching, and syncing server state in React applications. We’ll create a simple app that fetches data from an open-source API, and we’ll use Bootstrap for styling.
Goals
Build a web app to fetch data from below API using react-query
App should show below UI
Explanation of React Query for beginners:
Imagine you have a magical helper who can get you toys from a toy store whenever you ask. This helper not only brings you toys but also remembers them, so if you want the same toy again, the helper can get it for you without going to the store again. React Query is like this magical helper for our computer programs. It helps us get information from the internet and remembers it so that our programs can use it whenever needed.
Technically:
React Query is a library in React that makes it easier for us to fetch and manage data in our applications. It provides a set of tools to handle data fetching, caching, and updating the user interface when the data changes. Instead of writing a lot of complex code to interact with a server and manage the data in our app, React Query simplifies the process, making it more efficient and straightforward.
In technical terms, React Query uses a concept called "queries" to fetch data. A query is like a request to get information from a server, and React Query handles this process smoothly. It also helps with caching, which means storing data so that if we need it again, we don't have to fetch it from the server once more.
React Query is a helpful tool, especially when we are building React applications that need to interact with servers to get or send data. It's like having a reliable assistant, making our coding tasks more manageable and organized.
Prerequisites
Make sure you have the following installed:
- Node.js
- Create React App: Run the below commands to set up the project:
npx create-react-app react-query-webapp
npm install react-query
Steps
Step 1: Set Up the Project
cd react-query-webapp
npm install bootstrap
npm start
Step 2: Fetch Data from an Open-Source API
For this example, we’ll use the JSONPlaceholder API, a fake online REST API for testing and prototyping.
Update the contents of `src/App.js`
// src/App.js
import React from "react";
import { useQuery } from "react-query";
import Header from "./components/Header";
import "bootstrap/dist/css/bootstrap.min.css";
const fetchData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
return data;
};
function App() {
const { data, isLoading, error } = useQuery("todos", fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<Header title={"React Query"} />
<div className="container mt-5">
<h1>React Query Web App</h1>
<div className="card">
<div className="card-body">
<h5 className="card-title">Data from JSONPlaceholder API</h5>
<p className="card-text">{JSON.stringify(data)}</p>
</div>
</div>
</div>
</div>
);
}
export default App;
Update `src/index.js` to add provider component for react-query:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider, useQuery } from "react-query";
import App from "./App";
const queryClient = new QueryClient();
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</StrictMode>
);
Add a header in `src/components/Header.js`:
import React from "react";
export default function Header(props) {
return (
<nav className="navbar navbar-dark bg-dark">
<div className="container">
<div className="row m-auto">
<i className="fa fa-hand-pointer-o fa-2x text-white mr-2" />
<div className="text-light h2" data-testid="title">
{props.title}
</div>
</div>
</div>
</nav>
);
}
Step 3: Run the App
Run below command in terminal:
npm start
Visit http://localhost:3000 in your browser to see the react query app.
Conclusion
Congratulations! You’ve successfully implemented React Query in a basic web app. This powerful library simplifies data fetching and state management in React applications, making your code more efficient and maintainable. Feel free to explore more features and integrate React Query into your future projects.
Check out my YouTube channel for more content:
Next part in the series to create a simple Shopping Cart application demonstrating how useReducer simplifies state updates: