technology
Data Caching in React with Zustand and TanStack Query ( react-query )
Mastering React State: Exploring Effortless Management with Zustand and Tanstack
Welcome to a realm where React state management becomes a breeze! Discover the fusion of Zustand and Tanstack, a dynamic duo that redefines simplicity and efficiency in handling your application's state.
Embarking on a Seamless Coding Voyage: Zustand and Tanstack Unveiled
Let's embark on an exhilarating coding adventure, exploring how Zustand integrates seamlessly with Tanstack to revolutionize the way you manage state within your React application.
Fetching Animal Data: The Smart Way with Tanstack's React Query
Dive into our api service
file, where the magic of Tanstack's @tanstack/react-query
comes to life! Behold the brilliance of the useAnimals
hook, utilizing React Query to fetch animal data. This hook, cleverly linked with useAnimalStore
from our Zustand store, ensures efficiency by skipping API calls if data is already stored locally.
import { useQuery } from '@tanstack/react-query';
import { isEmpty } from 'lodash';
import useAuthStore from 'src/store/auths';
import AnimalService from '../services/animals';
import useAnimalStore from '../store/app';
export const useAnimals = () => {
const animalStore = useAnimalStore();
const { tokens } = useAuthStore.getState();
const { data, ...rest } = useQuery(
['animals/list'],
async () => {
const res = await AnimalService.getAnimals();
return res.data;
},
{
onSuccess: (res) => {
animalStore.setAnimals(res);
},
enabled: !!tokens?.access_token && isEmpty(animalStore.animals),
}
);
return {
data,
...rest,
};
};
Zustand Store: Power-Packed State Management at Your Fingertips
Enter the realm of useAnimalStore
โthe stronghold of state management prowess. This Zustand store not only defines state structures and their modifications but also shines with remarkable persistence capabilities. Seamlessly integrated with Tanstack, it employs localPersistStorage
for state persistence. More excitingly, optimize data fetching based on connectivity or intervals for performance boosts!
//the state value will automatically be persisted to and restored from localStorage
import { localPersistStorage } from '@utils/state-storage';
import { createStore } from '@utils/store-tools';
export type AnimalStateType = {
animals: Record<string,any>[] ;
};
type AnimalActionsType = {
setAnimals: (data: any) => Promise<void>;
};
export type AnimalStoreType = AnimalStateType & AnimalActionsType;
const useAnimalStore = createStore<AnimalStoreType>(
(set) => ({
animals: [],
setAnimals: async (value) => {
set({ animals: value });
},
}),
{
devtoolsEnabled: true,
persistOptions: {
name: 'animals-list',
storage: localPersistStorage,
},
}
);
export default useAnimalStore;
Amplifying Potential with Advanced Store Tools and Local Persist Storage
Empower your Zustand store with a suite of finely crafted store tools, enhancing its compatibility with Tanstack's prowess. The inclusion of localPersistStorage
ensures your application's resilience, securing data persistence across browser closures. Dive deeper into customization options to fine-tune fetching strategies based on connectivity or timed intervals for optimal performance.
//store-tools
import { create, StateCreator, StoreApi, UseBoundStore } from 'zustand';
import { devtools, persist, PersistOptions } from 'zustand/middleware';
interface ICreateStoreOptions<T, U> {
persistOptions?: PersistOptions<T, U>;
devtoolsEnabled?: boolean;
}
export function createStore<T extends object>(
createState: StateCreator<T>,
options?: ICreateStoreOptions<T, any>
): UseBoundStore<StoreApi<T>> {
let store = create(createState);
if (options?.persistOptions) {
store = create(persist(createState, options.persistOptions));
}
if (options?.devtoolsEnabled) {
store = create(devtools(createState));
}
if (options?.devtoolsEnabled && options?.persistOptions) {
store = create(devtools(persist(createState, options.persistOptions)));
}
return store;
}
//localpersiststorage, ps, you can use any storage you want, not just localstorage, but for this example, we will use localstorage
import { PersistStorage } from 'zustand/middleware';
export const localPersistStorage: PersistStorage<T> = {
getItem: (name) => {
const str = localStorage.getItem(name);
if (!str) return null;
return JSON.parse(str);
},
setItem: (name, value) => {
localStorage.setItem(name, JSON.stringify(value));
},
removeItem: (name) => localStorage.removeItem(name),
};
Embrace Hands-On Learning: Your Path to State Management Mastery
Engage with the provided code snippets! Dive into practical experimentation, tweak configurations, and witness the magical synergy of Zustand and Tanstack in action.
Embrace the Simplicity: A Conclusion of Empowerment
With Zustand and Tanstack in perfect harmony, complexity dissolves, paving the way for a robust yet straightforward state management ecosystem. Craft high-performing, maintainable React applications effortlessly, tailored to handle intricate state requirements with ease.
A World of Options: Your Input Matters in Continuous Evolution
Remember, the code we've showcased is just the tip of the iceberg! Customize performance, data-fetching strategies, and optimizations at your fingertips. Your feedback and exploration of different approaches are essential for ongoing enhancement and refinement.
Set Sail on Your Zustand Journey: Unlocking Limitless Horizons
Elevate your state management game with the seamless fusion of Zustand and Tanstack. Dive into the code, explore the documentation, and unlock the immense potential to transform your React projects.
Are you ready to unlock the power of Zustand within your applications? Let's code, innovate, and revel in the simplicity that awaits!
Experiment and adapt the provided code to suit your project's unique requirements. Dive deeper into Zustand's and Tanstack's documentation for a transformative development experience!
Embrace the simplicity and efficiency of Zustand, perfectly intertwined with Tanstack's prowess! ๐