React Hooks Deep Dive: Part 2 - useContext and useReducer
Published on
by Nguyễn Công Dũngreacthooksjavascripttutorial
React Hooks Deep Dive: Part 2 - useContext and useReducer
Welcome to Part 2 of our React Hooks series! Today we’ll explore useContext and useReducer for more advanced state management scenarios.
useContext Hook
The useContext hook allows you to consume context values without prop drilling:
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button className={`btn-${theme}`}>
Current theme: {theme}
</button>
);
}When to Use
- Sharing data across many components
- Avoiding prop drilling
- Global state that doesn’t change frequently
useReducer Hook
useReducer is like useState but for complex state logic:
import { useReducer } from 'react';
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>
);
}Benefits
- Predictable state updates
- Easier to test
- Better for complex state logic
Next Steps
In Part 3, we’ll learn about custom hooks and how to build reusable logic!