What is React Query and when you might need it in your Next 14 project

What is React Query and when you might need it in your Next 14 project

Everytime I come across a new technology in the ever expanding universe of tools and frameworks i.e. the React ecosystem, I start wondering how it fits in the picture and do I even need to use it in my projects.

I recently got to know about Tanstack Query (AKA React Query) and started digging deep to understand what it is all about. I went on Tanstack's official website and this is what they say on the landing page:

Toss out that granular state management, manual refetching and endless bowls of async-spaghetti code. TanStack Query gives you declarative, always-up-to-date auto-managed queries and mutations that directly improve both your developer and user experiences.

But WTH does this even mean?

In simple terms, React Query automates and simplifies fetching, caching, and managing server data in your web apps. It automatically handles all the tedious data-fetching tasks, keeping your app's data fresh and in sync with the server, without you having to write a ton of boilerplate code. Let me give you an example to make it clearer:

Before React Query:

You'd manually fetch data in your component, manage loading states, errors, and caching by yourself. It's like going to fetch water from a well every time you're thirsty, then boiling it, cooling it, and finally getting to drink it.

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    setIsLoading(true);
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => setError(error))
      .finally(() => setIsLoading(false));
  }, []);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {/* Render your data */}
    </div>
  );
}

After React Query:

React Query turns the whole process into a single function call. It's like having a smart fridge that not only fetches water for you but also ensures it's always at the perfect temperature whenever you need it.

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

function App() {
  const { data, isLoading, error } = useQuery('fetchData', () =>
    fetch('https://api.example.com/data').then(res =>
      res.json()
    )
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {/* Render your data */}
    </div>
  );
}

React Query handles all the heavy lifting behind the scenes. It automatically fetches data, caches it so you're not constantly asking for the same info, and helps keep your app's data up-to-date with the server. This makes your code cleaner, more efficient, and lets you focus on building cool features rather than wrestling with data management.

So I basically understood that using it with a React app could be really beneficial and improve the app's performance significantly for the end user.

But should I be using it in my Next.js 14 project that I'm building right now or would it just complicate things further?

You see, Next.js 14 already has a ton of integrations to make a performant web app like Server Actions, fetching data asynchronously in server components and ways to cache fetched data. Nonetheless, I found one major use case where using React Query with Next.js 14 could still be useful.

So, if you are building an application that has a page with posts or comments (e.g, a blog site) from other users, React Query could be used to control and revalidate the data live on your page.
What this means is that if a user A is currently on your dashboard where multiple blog posts are displayed and another user B adds a new post to the page, Next.js 14 would revalidatePath for user B so that they see the updated dasboard with the new post, but user A would still see the stale dashboard until they refresh their browser.

This is a good video explaining how to implement React Query in such use cases. That being said, I have decided not to add React Query in my Next.js application right now. Sure, it would improve the user experience a tad bit but it feels like over engineering for a very tiny edge case in my application. :)

Do let me know in the comments if you find other areas of improvement in your Next 14 applications that could benefit from React Query.

Say hi to me on Twitter and LinkedIn. :)