Redux vs Context API
Both Redux and Context API are used to manage state in a React application, but they serve different purposes and works in different scenarios.
1. Context API (Best for Small Apps)
?? What it is: Built-in React feature for passing data without prop drilling.
?? Best for: Small to medium apps with simple state management.
?? How it works: Uses React.createContext() to share state between components.
Example: Theme Switcher (Context API)
Imagine you have a theme switcher (Light/Dark Mode). Using Context API, you store the theme state and share it across components.
import { createContext, useContext, useState } from "react";
// Create Context
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
// Custom Hook to use Theme
const useTheme = () => useContext(ThemeContext);
// Example Component
const ToggleTheme = () => {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Switch to {theme === "light" ? "Dark" : "Light"} Mode
</button>
);
};
// Wrap App with Provider
const App = () => (
<ThemeProvider>
<ToggleTheme />
</ThemeProvider>
);
export default App;
? Simple and easy to use
? No need to install extra libraries
? Not great for large-scale applications with complex state
2. Redux (Best for Large Apps)
?? What it is: A third-party library for managing global state in large apps.
领英推荐
?? Best for: Large apps with complex state (user authentication, cart, notifications, etc.).
?? How it works: Uses a central store where components dispatch actions to modify state.
Example: Shopping Cart (Redux)
Imagine you have an e-commerce app where users add/remove products from a cart. With Redux, the cart state is global and can be accessed by any component.
import { configureStore, createSlice } from "@reduxjs/toolkit";
import { Provider, useDispatch, useSelector } from "react-redux";
// Create a Cart Slice
const cartSlice = createSlice({
name: "cart",
initialState: [],
reducers: {
addToCart: (state, action) => {
state.push(action.payload);
},
removeFromCart: (state, action) => {
return state.filter((item) => item.id !== action.payload);
},
},
});
const { addToCart, removeFromCart } = cartSlice.actions;
const store = configureStore({ reducer: { cart: cartSlice.reducer } });
// Example Component: Add Item to Cart
const Product = ({ product }) => {
const dispatch = useDispatch();
return (
<div>
<h4>{product.name}</h4>
<button onClick={() => dispatch(addToCart(product))}>Add to Cart</button>
</div>
);
};
// Example Component: View Cart
const Cart = () => {
const cart = useSelector((state) => state.cart);
return (
<div>
<h3>Shopping Cart</h3>
{cart.map((item) => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
};
// Wrap App with Redux Provider
const App = () => (
<Provider store={store}>
<Product product={{ id: 1, name: "Laptop" }} />
<Cart />
</Provider>
);
export default App;
? Scalable for large apps
? Predictable state with actions & reducers
? More boilerplate code
? Requires extra setup & learning
When to Use What?
??Use Context API if you just need a simple global state (theme, auth).
??Use Redux when managing complex app state across multiple components.
Software Engineer @Sopra Steria || AIR-1532 CS Gate"24
4 周CFBR