React Query: Data Fetching Made Easy

React Query: Data Fetching Made Easy

ยท

3 min read

I recently began utilizing React Query in my work and I must say it has been a game-changer. The simplicity and efficiency it brings to my development process are remarkable. Today, I want to delve into the world of React Query and guide you through getting started with this powerful library. So, without further ado, let's dive in!

What is React Query?

React Query is a powerful library that simplifies data fetching and state management in React applications. In just a few moments, let's uncover the remarkable advantages it offers and witness a live example in action!

  • How to install React Query
$ npm i react-query
# or
$ yarn add react-query
  • We will import QueryClient, and QueryClinderprovider to start working with react query
import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from 'react-query';
import App from './App';

// Create a new instance of QueryClient
const queryClient = new QueryClient();

// Render the app
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);
  • React Query gives use two hooks useQuery and useMutation.

  • we use useQuery to fetch data whenever needed. On the other hand, useMutation is utilized for handling mutation operations, such as updating or deleting data.

  • The useQuery hook takes in three parameters: the query key, the data fetching function, and optional query options.

  • useMutation hook in React Query takes in two parameters: the mutation function and optional mutation options.

  • I will provide an example using useQuery.

import { useQuery } from 'react-query';

function User() {
  const { isLoading, error, data } = useQuery('userData', async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const json = await response.json();
    return json;
  }, 
  {
    onSuccess: (data) => {
      console.log('Query succeeded with data:', data);
    },
    onError: (error) => {
      console.log('Query failed with error:', error);
    },
  }
  );

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>User Data</h1>
      <ul>
        {data.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default User
  • 'userData' represents the query key used to identify and cache the fetched data.

  • The second parameter represents the function responsible for fetching the data.

  • third is the options parameter. it is used to control the certain behaviour of the query by enabling or disabling certain conditions. In the given example, we use onSuccess and onError to specify actions to be taken upon successful data fetching or in case of an error.

  • isLoading represents a boolean value indicating whether the data is currently being fetched. data contains the fetched data, and error holds any error that occurred during the fetching process

And that concludes our discussion on React Query! I hope this blog has provided you with a solid understanding of React Query and its benefits. If you're hungry for more knowledge, I encourage you to dive deeper by exploring the documentation.

Thank you for investing your time in reading this blog, and I wish you nothing but success and happiness in your coding journey! Happy coding! ๐Ÿ˜Š๐Ÿ˜Š

ย