React Query
Tags: react, javascript, programming, webdev
Published: 2022-11-22 11:09:52

Any kind of Feedback is welcome, thanks and I hope you enjoy the article.🤗

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmptotmkqib8zj7razxt.gif)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88sddb4bibr18gn0s5zq.gif)

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](https://react-query-v3.tanstack.com/) for more insight

**index.js**

```javascript

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>
);

```

**Example.jsx**

```javascript
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>

)}


```

**App.jsx**

```javascript

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


function App () {

<main>
<Example />
</main>

}

```



<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

**Thank you, Please follow me**

[![HTML](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://linkedin.com/in/ifeanyi-thankgod-chima)&nbsp;[![GitHub](https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/masterifeanyi)