How to use the useQuery hook for data fetching in Next.js



Image not found!!


In Next.js, you can use the useQuery hook provided by the react-query library for data fetching. react-query is a popular library for managing and caching asynchronous data in React applications. To use useQuery in Next.js, you'll first need to install the library. You can do this using npm or yarn:

bash
# Using npm npm install react-query # Using yarn yarn add react-query

Once you have react-query installed, you can use the useQuery hook in your components. Here's an example of how you might use it:

  1. Import the necessary dependencies:
jsx
// pages/index.js import { useQuery } from 'react-query';
  1. Define a function to fetch your data. This function will be used as the query key for caching purposes:
jsx
// pages/index.js const fetchData = async () => { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; };
  1. Use the useQuery hook in your component, passing the query key and the function to fetch the data:
jsx
// pages/index.js const HomePage = () => { const { data, error, isLoading } = useQuery('myData', fetchData); if (isLoading) { return <p>Loading...</p>; } if (error) { return <p>Error: {error.message}</p>; } return ( <div> <h1>My Data</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }; export default HomePage;

In this example:

  • The useQuery hook takes two parameters: the query key ('myData' in this case) and the function (fetchData) that will be used to fetch the data.

  • The data variable contains the result of the data fetching.

  • The error variable contains any error that occurred during the fetching process.

  • The isLoading variable is a boolean indicating whether the data is still being fetched.

  • The component displays different content based on the loading state and any potential errors.

This is a basic example, and you can customize it further based on your application's needs. The react-query library provides additional features for handling caching, invalidation, and more. Check the library's documentation for more advanced usage.