React State Management Comparison
Choose the right state management solution for your React project.
Redux Toolkit
// store/userSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const fetchUser = createAsyncThunk('user/fetch', async (id) => {
const response = await fetch(`/api/users/${id}`);
return response.json();
});
const userSlice = createSlice({
name: 'user',
initialState: { data: null, loading: false },
reducers: {
logout: (state) => { state.data = null; }
},
extraReducers: (builder) => {
builder
.addCase(fetchUser.pending, (state) => { state.loading = true; })
.addCase(fetchUser.fulfilled, (state, action) => {
state.loading = false;
state.data = action.payload;
});
}
});
Zustand - Simpler Alternative
import { create } from 'zustand';
const useStore = create((set, get) => ({
user: null,
loading: false,
fetchUser: async (id) => {
set({ loading: true });
const user = await fetch(`/api/users/${id}`).then(r => r.json());
set({ user, loading: false });
},
logout: () => set({ user: null }),
}));
// Usage in component
function Profile() {
const { user, loading, fetchUser } = useStore();
// ...
}
Jotai - Atomic State
import { atom, useAtom } from 'jotai';
const userAtom = atom(null);
const loadingAtom = atom(false);
// Derived atom
const isLoggedInAtom = atom((get) => get(userAtom) !== null);
// Async atom
const userDataAtom = atom(
(get) => get(userAtom),
async (get, set, id) => {
set(loadingAtom, true);
const user = await fetch(`/api/users/${id}`).then(r => r.json());
set(userAtom, user);
set(loadingAtom, false);
}
);
When to Use What
- Redux Toolkit: Large apps, complex state logic, team projects
- Zustand: Simple to medium apps, quick setup
- Jotai: Fine-grained reactivity, atomic updates
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!