umma.dev

React Query

A small introduction to React-Query with example code.

What is React Query?

React-query enables you to handle data in a quick and easy way. It comes with a number of features which enable you to cache data, integrate with TypeScript, GraphQL, React Native, and much more…

Set Up

npm i @tanstack/react-query

Add the query client in index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { QueryClient, QueryClientProvider, useQueryClient } from 'react-query'
import App from './App'

const queryClient = new QueryClient()

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <React.StrictMode>
      <App/>
    </React.StrictMode>
  </QueryClientProvider>,
  document.getElementById('app')
)

Set up data file to handle request (below is a GET with axios)

import { useQuery } from 'react-query'
import axios from 'axios'

const getData = async () => {
  const { data } = await axios.get(
    'https://www.yourapi.com'
  )
  return data
}

export default function useData() {
  return useQuery('myData', getData)
}

Using the data in a component

import useData from '../data/useData'

const ExampleComponent = () => {
  const { status, data, error } = useData()
  return (
    <>
      {status === 'loading' ? (
        'Loading...'
      ) : status === 'error' ? (
        <span>Error: {error.message}</span>
      ) : (
        data?.map((someData) => (
          <div>{someData.name}</div>
        ))
      )}
    </>
  )
}
export default ExampleComponent