DEV Community

Brighton Mboya
Brighton Mboya

Posted on

Getting Started in React Query.

React Query is by far hands-down the best library for data-fetching for React Apps. ~Tanner Linsley.

Mental Model on react-query

In this series, we will be looking at how React Query can help you solve all of your server state problems. React Query is a library that helps you manage server state to your React Applications. Client State is very different from Server State and its good to establish a proper mental model before we even get to React Query.
Suppose you have a hamburger menu that controls if a sidebar menu is opened or not, this state can easily be controlled by built-in solution in React, React.useState(). Server State however is much more different. To give an example consider you have a sign up form with a button. Once this button is clicked, it should send the user information to a data base. What happens when the user's network suddenly drops when they click the button, what happens if the user clicks the button more than once. These are very simple mutation scenarios that you need to think of while writing your React Apps. With React Query all these situations and many more are covered.
With the proper mental model in mind, let's go ahead and install the library. This assumes you have a react app already running. Paste this command in your terminal or cmd.
npm i @tanstack/react-query.

Query Client and Query Client Provider

Another powerful feature of the library is the Query Client, which interacts with the cache for your data, and the Query Client Provider which should be wrapped in the top level of your app i.e the App.tsx file.

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient()

function App() {
  return <QueryClientProvider client={queryClient}>
Enter fullscreen mode Exit fullscreen mode

What happened here is that we have created the queryClient and we have wrapped MyComponent using the QueryClientProvider and providing the client.

Then we need to define the MyComponent function. We will now use useQuery from react-Query. This hook accepts three arguments or so. The first one is the query key, second is the function to fetch the data, and the last is the option.

  1. The queryKey: This is a unique identifier that will tell React-Query to differentiate your data. When this key changes, React Query will refetch your data again. It is good to think of this key as the key you pass to the dependency array in React.useEffect(). It is an array and anything can be placed in this array, i.e strings, objects, etc. E.g
    const queryKey = ['users', {id, location}]

  2. The queryFunction. This is a function which returns a promise that is used to fetch the data. You can use the built in fetch() function or any other fetching library of your choice e.g Axios. as long as it returns a promise, it should work well. E.g

const fetchUsers = () => return fetch("").then(res => res.json)
Enter fullscreen mode Exit fullscreen mode
  1. The options: This is an object where you can specify different options to your query. This include staleTime (how long does the query considered fresh until fetched again), initialData (the data passed to your query before fetched), onError (a call back function that gets executed once the query fails) etc. To get more options have a look at the docs.

With that in mind, let's use a dummy api to fetch a list of random employees.

function MyComponent() {
  const {data, isLoading, isError} = useQuery(["employees"], () => {
    return fetch("").then((res) =>

  if (isLoading) return <p>Loading ...</p>
  if (isError) return <p>{Error.message}</p>

  return <ul>
    { => (

Enter fullscreen mode Exit fullscreen mode

What happened here is that the useQuery gives us back a couple of things and we used object destructing to get the ones we want. Now if the query is loading (isLoading) we show a loading state and likewise for the error. On the return block we accessed the data property which our api gives us and we displayed the employee_name. You can check the console output to get a sense on why we traversed the data this way.

And there you have it, you have successfullymade your first query. To get more in depth, check out the docs and you can go ahead and play with the sandbox.

If you found this helpful, give it a like and follow me on twitter

Top comments (0)