With React 16.8’s Context API improvements, do you still need Redux? The answer is nuanced. Here’s my take on when to use each.
Context API
Context is built into React. Great for passing data without prop drilling:
const ThemeContext = React.createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
<MainContent />
</ThemeContext.Provider>
);
}
function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return <button className={theme}>Click me</button>;
}
Redux
Redux is a predictable state container. Actions describe what happened, reducers update state:
// Actions
const addTodo = (text) => ({ type: 'ADD_TODO', payload: text });
// Reducer
function todosReducer(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [...state, { text: action.payload, done: false }];
default:
return state;
}
}
// Store
const store = createStore(todosReducer);
// Component
function TodoList() {
const todos = useSelector(state => state);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(addTodo('New'))}>Add</button>
);
}
When to Use Context
- Theme, locale, user preferences
- Authenticated user data
- Simple state shared across few components
- State updates are infrequent
When to Use Redux
- Complex state with many updates
- Need for middleware (async, logging)
- Time-travel debugging valuable
- Large team benefits from predictable patterns
My Rule of Thumb
Start with Context. Add Redux when Context becomes unwieldy or you need its ecosystem (DevTools, middleware, etc.).
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.