DEV Community

Jad
Jad

Posted on • Updated on

Migrate from `old way of fetching data` to react-query..

Introduction

Fetching data is an essential part of any product developers make nowadays, as React developers we've been doing so much to fetch some data from a server and we spend more time to keep this data synced with the one on the server.

But now as things are getting faster and faster the community had to think of a faster and more opinionated way to handle fetching data for us developers. one of the best tools is react-query.

What is react-query?

per the docs react-query is

often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze.

shall we stop talking and start writing some code!.

Before react-query we used to write all this code to fetch a piece of data from a server, keeping a state (loading,failed, succeed) of each stage of fetching these data

old way to fetch data without react-query

to compare between old way and react-query, and how it makes this simpler than before, take a look at the code below.

fetch code with react-query

How beautiful/simple is this, isn't much cleaner and readable.
react-query simplifies and does everything on it's side and just returns the data/state that we are interested in.

we just pass the url we need the data from and boom we have it, no more useEffect(), setState() or async function inside useEffect(), and we can also track the fetching state if it still loading or failed.

Important thing to notice..

using useEffect() to fetch data is somehow considered a bad practice, as per official docs

By using useEffect() hook, you tell React that your component needs to do something after render.

which will take more time as react always seeks to finish rendering first then calls functions inside useEffect,
But react-query useQuery() solves this issues by start fetching data in parallel with rendering, which of course time saver.

Last but not least

react-query does more more than just fetching data from a server,it has other methods to make our life easier, as mutate, prefetching data, invalidate cached data and of course caching, it even have it's built-in devTool I just wrote this article as an introduction for react-query.
You can have more information about it's capabilities by reading the docs.

I hope this gave you an overlook of this awesome tool. Feel free to leave a comment with suggestions, questions, or if you think some changes have to be done in the article.

Top comments (0)