Unlocking the Power of React Query and Suspense
What is useQuery?
React Query’s useQuery
Hook is a game-changer for managing states in functional apps. It fetches data based on a query passed to it and stores the data in its parent variable. A query consists of a unique key and an asynchronous function that is acted upon. The unique key is used for internal operations like fetching data, caching, and refetching data linked to the query.
Key Features of useQuery
- Fetching Data:
useQuery
simplifies data fetching by providing a straightforward way to fetch data from a source. - Prefetching: Prefetching is a powerful feature that loads data in the background, so your app doesn’t have to send a new request to retrieve data each time a user needs it.
- Caching: Caching stores data for a period of time, allowing your app to retrieve data from memory without having to re-query.
Building the App
Let’s build a simple recipe app that fetches and renders data from an API using React Query’s useQuery
Hook.
Setup
npm install react-query
mkdir recipe-app
cd recipe-app
touch index.jsx queries.jsx Recipe.jsx Recipes.jsx Button.jsx
API
const express = require('express');
const app = express();
const recipes = [
{ id: 1, name: 'Recipe 1' },
{ id: 2, name: 'Recipe 2' },
//...
];
app.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Components
// queries.jsx
import { useQuery, useQueryClient } from 'eact-query';
const fetchRecipes = async () => {
const response = await fetch('/api/recipes');
return response.json();
};
export const useRecipes = () => {
return useQuery('recipes', fetchRecipes);
};
// Recipe.jsx
import React from 'eact';
import { useRecipes } from './queries';
const Recipe = () => {
const { data, error, isLoading } = useRecipes();
if (isLoading) {
return
;
}
if (error) {
return
;
}
return (
{data.name}
{data.description}
);
};
export default Recipe;
Running the App
Finally, we run our app and see Suspense in action. When a recipe is being loaded, the Suspense fallback message is displayed when there’s a delay in data fetching. The fetched recipe data is stored in cache and is immediately displayed again if the same recipe is loaded again.
// index.jsx
import React from 'eact';
import ReactDOM from 'eact-dom';
import { ReactQueryCacheProvider, QueryCache } from 'eact-query';
import { Suspense } from 'eact';
import Recipe from './Recipe';
const queryCache = new QueryCache();
ReactDOM.render(
Loading...}>
,
document.getElementById('root')
);