State Management in React: Patterns and Best Practices
August 8, 2024•2 min read
ReactState ManagementFrontendRedux
# State Management in React: Patterns and Best Practices
Effective state management is crucial for building maintainable React applications. This guide covers various state management approaches.
## Local State
Use useState for component-specific state:
```typescript
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
```
## Context API
For shared state across components:
```typescript
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
```
## Zustand
Lightweight state management:
```typescript
import create from 'zustand';
interface UserStore {
user: User | null;
setUser: (user: User) => void;
}
const useUserStore = create<UserStore>((set) => ({
user: null,
setUser: (user) => set({ user }),
}));
```
## Redux Toolkit
For complex state management:
```typescript
import { createSlice } from '@reduxjs/toolkit';
const userSlice = createSlice({
name: 'user',
initialState: { user: null },
reducers: {
setUser: (state, action) => {
state.user = action.payload;
},
},
});
```
## Choosing the Right Solution
- **Local State**: Component-specific data
- **Context API**: Shared state within a tree
- **Zustand**: Simple global state
- **Redux**: Complex state with time-travel debugging
## Conclusion
Choose state management based on your application's complexity. Start simple and scale up as needed.