Beginners Guide To React Query

Table of Content

  1. What is React Query
  2. Why React Query
  3. How React Query Works
  4. Installing React Query
  5. Quick Start on querying data using React Query
  6. Conclussion

What is React Query

React query is a new custom hooks for handling all forms of asynchronous functions in you react app. It essentially enables you to fetch, cache and update all your asynchronous data in react without tampering with any state in your app, this reduces the amount of codes and increases the efficiency of all the logical code you write to fetch data. React Query handles caching, background updates and stale data out of the box with zero-configuration. All these were extra codes and logical thinking before react query came around.

Why React Query

As mentioned earlier, it makes us write shorter codes and makes our code more efficient.

If one understand promises, and how asynchronous functions works already in javaScript, its easier to jump into react query and see the advantages that comes with it.

Most of it functionality can be performed without interacting with any form of state manager or reducers in our app.

How React Query Works

Configuring React Query and working with it is pretty easy for a beginner cause it comes almost ready to be used and with options to fit every beginners use case. It has designated hooks for infinite-loading, pagination and mutation, all this makes updating our data easy.

How to get Started with React Query

To get started with react query we need to install it on the project we are working on. This can be done using either NPM or Yarn

The syntax for the installation goes as follow

NPM

npm install react-query --save

Yarn

yarn add react-query

After this we can now go ahead to use react query in our project.

Quick Start

A quick start to querying data using use Query. In this guide we will source our data from jsonplaceholder.typicode and display the title of the data.

Note: You're not explaining what your code does.

import React from "react";
import { useQuery } from "react-query";

const Post = () => {
  const url = "https://jsonplaceholder.typicode.com/todos/1";
  const fetchPost = async () => {
    let res = await fetch(url);
    let post = await res.json();
    return post;
  };
  const { data, status } = useQuery("post", fetchPost);
  return (
    <div>
      {status === "success" ? (
        <h1>{data.title}</h1>
      ) : (
        <div>your data is still loading....# # </div>
      )}
    </div>
  );
};

export default Post;