DEV Community

Cover image for React-query series Part 1: Basic react-query setup
Emmanuel Nnajiofor
Emmanuel Nnajiofor

Posted on • Edited on

50 12

React-query series Part 1: Basic react-query setup

Hey everyone!

So after a few years as a frontend developer, I have decided to
write my first article. You have no idea the fear I had to
conquer (or maybe you do), 😟 but there is no point hiding in your shell right ?

Sections

Intro

React-query is a superlight library for fetching, updating and synchronizing server state. With react-query, you don't have to write your
data-fetching logic (Who likes all that setting of loading, error and data state huh ? 🤷‍♀️ ), You
don't also need global store libraries like redux or
zustand to make your server state global or persistent. Even if a
global store is used in your application, it is restricted to only
client state like user settings etc, thereby reducing your
code size by a ton.
Although this library has a wonderful documentation, I have found that it can be daunting for beginners and thus, a need for a no-nonsense simple series to get beginners quickly setup to using react-query.
You can also skip to the part two: QueryClient configuration of this series

Prerequisite

  • Basic knowledge of react and hooks in react

Bootstrap our project

We bootstrap a basic react app by running npx create-react-app project-name

npx create-react-app react-query-setup
Enter fullscreen mode Exit fullscreen mode

We also install react-query library to our react app by running

npm i react-query. At the time of writing, react-query version is at 3.19.6

npm i react-query
Enter fullscreen mode Exit fullscreen mode

Setup react-query

To setup react-query, we need the QueryClientProvider. The
QueryClientProvider component is used to connect and provide a
QueryClient to your application; more or less, connect our
application to features react-query provides.
The QueryClientProvider component takes in a client prop. This
prop is in turn, supplied the queryClient instance. You can supply
the queryClient instance a custom config object as a param if
you'd like to set your own defaults. You can read about some
important defaults that come with react-query here.

import { QueryClient, QueryClientProvider } from 'react-query';

/*create and use a custom config object.Normally, I'd put this in another file and export
*/
const queryClientConfig = {
    defaultOptions: {
      queries: {
        retry: 2,
        refetchOnMount: "always",
        refetchOnWindowFocus: "always",
        refetchOnReconnect: "always",
        cacheTime: 1000*30, //30 seconds
        refetchInterval: 1000*30, //30 seconds
        refetchIntervalInBackground: false,
        suspense: false,
        staleTime: 1000 * 30,
      },
      mutations: {
        retry: 2,
      },
    },

 const queryClient = new QueryClient(queryClientConfig)

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

Additionally, you can add the ReactQueryDevTools component to debug and visualize your queries on your development environment.

import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';

/*create and use a custom config object.Normally, I'd put this in another file and export
*/
const queryClientConfig = {
    defaultOptions: {
      queries: {
        retry: 2,
        refetchOnMount: "always",
        refetchOnWindowFocus: "always",
        refetchOnReconnect: "always",
        cacheTime: 1000*30, //30 seconds
        refetchInterval: 1000*30, //30 seconds
        refetchIntervalInBackground: false,
        suspense: false,
        staleTime: 1000 * 30,
      },
      mutations: {
        retry: 2,
      },
    },

 const queryClient = new QueryClient(queryClientConfig)

 function App() {
   return  <QueryClientProvider client={queryClient}>
       {/* The rest of your application */}
       <ReactQueryDevtools initialIsOpen={false} />
     </QueryClientProvider>
 }
Enter fullscreen mode Exit fullscreen mode

In the next part of this series, we will talk more on what each key-value in the queryClientConfig object does for queries and mutations.

I'd really appreciate a 💖 if this article has helped you.
Thank you!

Follow me on twitter @NnajioforEmma10

Credits

Image: Logrocket: What is new in react-query 3 by Lawrence Eagles.

React-query documentation

Sections

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️