Context API vs Redux
Understand the differences between Context API and Redux for state management in React.
1. What is the Context API?
The Context API is a built-in React feature that allows you to share state across components without passing props down manually through every level of the tree.
import React, { createContext, useContext } from 'react'; // Create a Context const UserContext = createContext(); function App() { return (); } function Profile() { const user = useContext(UserContext); return Welcome, {user.name}!
; } export default App;
Explanation: The UserContext
shares data (user name) across the tree, making it accessible to the Profile
component without prop drilling.
2. What is Redux?
Redux is a popular library for state management that centralizes application state in a single store. It works with reducers and actions to update the state predictably.
// Redux example import { createStore } from 'redux'; const initialState = { counter: 0 }; function counterReducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { counter: state.counter + 1 }; case 'DECREMENT': return { counter: state.counter - 1 }; default: return state; } } const store = createStore(counterReducer); store.dispatch({ type: 'INCREMENT' }); console.log(store.getState()); // { counter: 1 }
Explanation: Redux uses a store to manage the application's state. Actions are dispatched to update the state predictably using reducers.
3. Comparison
Feature | Context API | Redux |
---|---|---|
Scope | Best for small to medium apps | Best for large-scale apps |
Learning Curve | Low | Medium to High |
Performance | May cause unnecessary re-renders | Efficient with middleware |
Community | Native to React | Large ecosystem |
4. When to Use Each
- Context API: Use for simple state sharing or when working with React-only projects.
- Redux: Use for complex state management, especially when working with middleware, dev tools, or asynchronous logic.