Member-only story
Fetch, Cache, and Update Data Effortlessly with React Query

React Query is a library that aims to make data fetching and data caching so easy that you’ll feel like you’re dreaming. If you’re a React developer, you should start using it today. I remember the days that developers (including me) were using Redux to store the data fetched from the API. Oh! That was so ducked-up! But not today because we are going to play around with React Query!
Installing React Query
Let’s do a quick setup. First, you should install the package via yarn add react-query
or npm install react-query
. After you install React Query, you will need to create an instance of the Query Client class and pass it to the Query Client Provider component:
Query Client is the heart of React Query! With Query Client, you can fetch/prefetch queries, get/set query data, refetch/invalidate queries, and a lot more. For now, all you need to know is that this Provider component wraps all your application components and shares the query client instance with the children using React Context. If you need to access the Query Client inside the children components, you can do it using useQueryClient
hook:
You can also configure the query client but we skip it for now and go with the defaults. Now, let’s fetch some queries!
Fetching Data with useQuery Hook
In order to query for data using React Query, you will need two things:
- Query Key: This key is used for refetching, caching, and sharing the queries throughout your application.
- Query Function: A function that returns a promise (resolves data or throws an error)