DEV Community 👩‍💻👨‍💻

Cover image for React Query
Ifeanyi Chima
Ifeanyi Chima

Posted on • Updated on

React Query

I've always fetched data with UseEffect and If you are coming from a class component background, this hook will replace your componentDidMount and componentDidUpdate functions, and this is a must-know hook.

Unlike UseEffect, we have to handle our loading state, error and setting our fetched data(response) to a state that holds the object we got back from the request made to the server.

Image description

React Query saves you the stress as the useQuery hook returns the isLoading state, error state, and data itself. It also returns the isFetching, refetch, isSuccess, and many more useful states and functions.

The useQuery hook could take in 3 arguments
• The first argument is the name of the Query or key, which could be an array or a string.
• The second argument is the fetcher function that requests data from the server.
• The third which is optional is an object that takes in the configuration on how we want our data served to the users, say we want to determine the staleTime of our data, refetch data whenever the component mounts , trigger a function on successful fetch, onError and many more.

Image description

Just as Redux, MobX, and Zustand are client-state libraries that can be used to store asynchronous data, React Query handles the Server state as it provides valuable tools to improve the reliability of server data in terms of invalidating data, marking data as stale, prefetching, refetching, caching and many more.

Attached 👇🏽 is a code snippet that describes how to fetch Data using react Query in your react applications.
Be sure to check out the Documentation for more insight

index.js


import {QueryClient, QueryClientProvider} from "react-query";
import {ReactQueryDevtools} from "react-query/devtools"; // this helps monitor performance

const queryClient = new QueryClient(); // this allows the queryClient to be available to the entire app

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
      <ReactQueryDevtools initialIsOpen />
    </QueryClientProvider>
  </React.StrictMode>
);

Enter fullscreen mode Exit fullscreen mode

Example.jsx

import {useQuery} from "react-query"


function Example () {

// Define your fetcher function as you would have done with useEffect
const fetchData = async () => {
  return await axios.get("https://jsonplaceholder.typicode.com/posts")
} 


const {isLoading, data, error,} = useQuery("nameOfCache/Query/Key", fetchData)

if (isLoading) return "Loading.." // returns Loading if the data is yet to be received from the server.

if (error) return <p> Error </p>  // returns an error after 3 retries if there was en error while fetching data.

return (

<div>
{ data.map((item) => {

return (

<div key={item.id}>

<h1>{item.name}</h1>
<p>{item.title}</p>

</div>


)}

)}

</div>

)}


Enter fullscreen mode Exit fullscreen mode

App.jsx


import React from "react"
import Example from "./components/Example"


function App () {

<main>
<Example />
</main>

}

Enter fullscreen mode Exit fullscreen mode

Thank you, please follow me

Buy Me A Coffee

twitter
github
linkedin

Top comments (1)

Collapse
 
aqnorman profile image
AQnorman

Thanks!, I need this.

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now