React Query is data fetching and caching library, it is best alternative for Redux store. The library uses hooks to fetch and store data.

First up all install the dependency

yarn add react-query

Provider

Add react-query provider in _app.tsx , lets import and create QueryClinet, wrap Component with Query client provider.

export default function SignUp() { import '../styles/globals.css'  import type { AppProps } from 'next/app'  import { Hydrate, QueryClient, QueryClientProvider } from 'react-query'  import { ReactQueryDevtools } from 'react-query/devtools'  import React from 'react';    function MyApp({ Component, pageProps }: AppProps) {    const [queryClient] = React.useState(() => new QueryClient())    return (             <QueryClientProvider client={queryClient} >          <Component {...pageProps} />        </QueryClientProvider>        );  }  export default MyApp  

Hooks

The second step is to create DataFetchers which is function to fetch data using fetch or axios from an API. It is common practice to place them in folder called hooks.

Also we need to export the new Hook which using the DataFetchers.

import { useQuery } from "react-query";  import { Category } from "../types/category";        export const fetchCategories = async () => {      const res = await fetch('http://localhost:3000/api/categories')      const data = await res.json();      return data.categories  }         export const useCategories = () => {    return useQuery<Category[],Error>('categories', () => fetchCategories(), {      refetchInterval: 1000    })  }

TypeScript requires types in order to avoid undefined error , so that mind to create the Category type.

export interface Category{    id: number;    name: string;  }   

In the hook we use useQuery to create query with a unique key, categories, this will allow us to invalidate and force to re-fetch the data when ever we want.

All the component using this query will share the same data.

Note that we need not create a global state for updating all UI

Use the Hook

In any component we can place a hook call which return a set of objects and can use the data in any component we want.

const {data,isLoading} = useCategories();  ... return( ....  {data && data.map((cat: { name: Category }, index: React.Key | null | undefined) => (            <div key={index}> {cat.name} </div>          ))}  ...  )

Invalidation of query save for another posts, hope got the point.


This free site is ad-supported. Learn more