Sitemap

How to Efficiently Manage State and Data with TanStack React

5 min readNov 18, 2024

In modern React applications, managing state and data flow is often a complex and challenging task. Whether you’re building a small app or a large-scale enterprise solution, handling state in a clean and maintainable way is crucial for performance and scalability. This is where TanStack React comes in — an intuitive set of libraries designed to handle state management and data fetching with minimal boilerplate.

In this post, we’ll dive into the key features of TanStack React, show how to integrate it into your project, and explore some common use cases to help you streamline state and data management.

What is TanStack React?

TanStack React is a collection of libraries that aims to simplify common challenges in React development, such as state management, data fetching, and caching. Its most well-known library is React Query, but TanStack also includes tools for routing (TanStack Router), table management (TanStack Table), and more.

One of the standout features of TanStack React libraries is their declarative nature, which allows developers to focus more on writing business logic and less on manual state updates and mutations.

Before that Let see how we write a basic custom hook

import { useState, useEffect } from 'react';

// Custom hook to fetch data with useEffect
export const useCustomFetch = (url: string) => {
// States for handling the data, loading, and errors
const [data, setData] = useState<any>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);

// useEffect to perform the data fetching
useEffect(() => {
// Avoid fetching if no URL is provided
if (!url) return;

// Function to fetch data
const fetchData = async () => {
setIsLoading(true); // Set loading to true before fetching

try {
const response = await fetch(url);

// Handle non-200 responses
if (!response.ok) {
throw new Error('Failed to fetch data');
}

// Parse the JSON data
const result = await response.json();
setData(result); // Set the fetched data
setIsLoading(false); // Set loading to false once data is fetched
} catch (error: any) {
setError(error.message); // Set error state
setIsLoading(false); // Set loading to false on error
}
};

fetchData(); // Call the fetch function

// Optionally clean up on unmount (useful for canceling fetch requests)
return () => {
setData(null); // Clean up state on unmount
setIsLoading(false); // Reset loading state
setError(null); // Reset error state
};
}, [url]); // Dependency array - re-run the effect if the URL changes

// Return the current data, loading, and error states
return { data, isLoading, error };
};
  1. Data Fetching with useEffect:
  2. Managing Loading State:
  3. Error Handling:
  4. Reusability:

But Api fecting is lot more that this like

  1. Cache
  2. Retry logic
  3. Optimized Performance
  4. Data Duplication

So now image rewriting this feature into that useCustomEffect , It will make the code bigger and still might not solve for all case and

  1. now we need to manage cache
  2. invalidate cache
  3. write re-fetch logic
  4. pass this data to other pages (could be done with redux)

Again a bigger code base for a fetch logic

So Now comes our Tanstack (Though i as other key feature we stick to fetch for this blog)

What is TanStack React?

TanStack React is a collection of libraries that aims to simplify common challenges in React development, such as state management, data fetching, and caching. Its most well-known library is React Query

One of the standout features of TanStack React libraries is their declarative nature, which allows developers to focus more on writing business logic and less on manual state updates and mutations.

Why Choose TanStack React?

Here are a few reasons why TanStack React is a great choice for your next project:

  • Minimal Boilerplate: Say goodbye to complex reducers, actions, and manual state management. TanStack simplifies state and data fetching.
  • Automatic Caching: With TanStack Query, you get built-in caching for your API requests, reducing redundant fetches and improving performance.
  • Optimized Performance: TanStack libraries use intelligent batching and memoization techniques to ensure optimal performance even with large datasets.
  • TypeScript Support: TanStack React provides excellent TypeScript support out of the box, making it easier to work with types and reducing runtime errors.

Setting Up TanStack React in Your Project

To get started, you’ll need to install TanStack libraries, such as React Query. Here’s how you can do it:

  1. Install Dependencies:
npm install @tanstack/react-query

2. Set up React Query Client:

In your main application file (e.g., index.tsx), you need to wrap your app with the QueryClientProvider and provide the QueryClient.

import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';

const queryClient = new QueryClient();

ReactDOM.render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>,
document.getElementById('root')
);
import { useQuery } from '@tanstack/react-query';

const fetchData = async () => {
const res = await fetch('https://api.example.com/data');
if (!res.ok) throw new Error('Network response was not ok');
return res.json();
};

export const useData = () => {
return useQuery(['data'], fetchData);
};

The above is the code for all feature i mentioned above literally that all..

We could use the useData in any where in the page it acts as server state API and other features like caching , re-fetching , Data Duplication , loading state , error state ,dependency etc….



import React from 'react';
import { useData } from './useData';

const DataComponent = () => {
const { data, error, isLoading } = useData();

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

return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};

export default DataComponent;

In this example:

  • useQuery automatically handles loading, error, and success states.
  • React Query automatically caches the data and will only re-fetch if needed (e.g., when the data is stale).

Conclusion

TanStack React provides a powerful set of tools to simplify state management and data fetching in React applications. By using React Query for handling server-side data and React Mutation for modifying data, you can streamline your application’s codebase while optimizing performance with built-in caching and error handling.

Whether you’re building a small personal project or scaling a large application, TanStack React offers flexible and efficient solutions that save time and reduce boilerplate code.

Happy coding!

If you haven’t already, give TanStack React a try in your next project and experience how it can make your development process smoother and more enjoyable. Feel free to drop any questions or feedback in the comments below!

https://tanstack.com/ — official docs

--

--

sKiridharan
sKiridharan

Written by sKiridharan

App developer and web development with django python . Learn by reading Practice by coding😍

No responses yet