Introduction
State management is one of the most important aspects of building React applications. In this article, we'll explore modern solutions for managing state effectively.
Local State with useState
For simple, component-level state, useState is still the go-to solution:
typescript
const [count, setCount] = useState(0);
const [user, setUser] = useState<User | null>(null);Global State with Zustand
Zustand provides a lightweight alternative to Redux:
typescript
import { create } from 'zustand';
interface StoreState {
count: number;
increment: () => void;
decrement: () => void;
}
const useStore = create<StoreState>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
// Usage
function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>{count}</button>;
}Server State with React Query
For server state, React Query is the industry standard:
typescript
import { useQuery, useMutation } from '@tanstack/react-query';
function Posts() {
const { data, isLoading, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
});
if (isLoading) return <Spinner />;
if (error) return <Error message={error.message} />;
return <PostList posts={data} />;
}Conclusion
Choose the right tool for the job: useState for local state, Zustand or Redux for global state, and React Query for server state.
Tags
ReactReduxZustandState ManagementFrontend
MH
Mahedi H Sharif
Full Stack Developer
Passionate about building scalable web applications and sharing knowledge with the developer community.