React — State Management
Local State
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
);
}
Context API
const AppContext = createContext();
function AppProvider({ children }) {
const [state, setState] = useState({
user: null,
theme: 'light'
});
return (
<AppContext.Provider value={{ state, setState }}>
{children}
</AppContext.Provider>
);
}
useReducer
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
State Management Libraries
# Redux
npm install @reduxjs/toolkit react-redux
# Zustand
npm install zustand
# Recoil
npm install recoil
Redux Example
// store.js
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; },
},
});
export const { increment, decrement } = counterSlice.actions;
export const store = configureStore({ reducer: { counter: counterSlice.reducer } });
// Counter.jsx
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
}
Mini Practice
Write React code that:
- Uses local state
- Implements Context API
- Uses useReducer
- Sets up Redux store
Up Next
Next: Learn about TypeScript in React.
Related Topics
Frequently Asked Questions about State Management
What is State Management in React?
State Management is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn State Management?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn State Management.
Why is State Management important in React?
State Management is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.