Introduction to Redux
Introduction to Redux
What is Redux?
Redux is a state management library often used with React to manage the application state in a
predictable way. It provides a centralized store that holds the state of your entire application, making
state management easier, especially for larger applications.
When to Use Redux
- Large Scale Applications: Redux is beneficial when managing complex state in large applications.
- Predictable State: If you need predictable state transitions and easy debugging.
- Centralized State Management: Useful when multiple components need to share the same state.
Key Concepts of Redux
1. Store: The single source of truth that holds the state of the application.
2. Actions: Plain JavaScript objects that describe changes in the state.
3. Reducers: Functions that take the current state and an action, and return a new state.
4. Dispatch: The method to send actions to the Redux store.
5. Selectors: Functions that extract specific pieces of state from the Redux store.
Advantages of Using Redux
- Centralized State: Makes it easier to manage and debug the state.
- Predictability: Ensures predictable state transitions.
- Middleware: Easily integrates middleware for handling asynchronous actions.
Introduction to Redux
Disadvantages of Using Redux
- Boilerplate Code: Requires writing a lot of boilerplate code.
- Learning Curve: Steeper learning curve compared to simpler state management solutions.
Setting Up Redux
1. Install Redux and React-Redux:
npm install redux react-redux
2. Create the Store:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
3. Provider Component:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
Introduction to Redux
document.getElementById('root')
);
Example: Building a Shopping Cart
Actions
// actions/cartActions.js
export const ADD_TO_CART = 'ADD_TO_CART';
export const REMOVE_FROM_CART = 'REMOVE_FROM_CART';
export const addToCart = (item) => ({
type: ADD_TO_CART,
payload: item
});
export const removeFromCart = (itemId) => ({
type: REMOVE_FROM_CART,
payload: itemId
});
Reducer
// reducers/cartReducer.js
import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/cartActions';
const initialState = {
Introduction to Redux
items: []
};
const cartReducer = (state = initialState, action) => {
switch(action.type) {
case ADD_TO_CART:
return {
...state,
items: [...state.items, action.payload]
};
case REMOVE_FROM_CART:
return {
...state,
items: state.items.filter(item => item.id !== action.payload)
};
default:
return state;
};
export default cartReducer;
Store
// store/index.js
import { createStore, combineReducers } from 'redux';
Introduction to Redux
import cartReducer from '../reducers/cartReducer';
const rootReducer = combineReducers({
cart: cartReducer
});
const store = createStore(rootReducer);
export default store;
Using Redux in Components
// components/Cart.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addToCart, removeFromCart } from '../actions/cartActions';
const Cart = () => {
const items = useSelector((state) => state.cart.items);
const dispatch = useDispatch();
return (
<div>
<h2>Shopping Cart</h2>
<ul>
{items.map((item) => (
Introduction to Redux
<li key={item.id}>
{item.name} - {item.price}
<button onClick={() => dispatch(removeFromCart(item.id))}>Remove</button>
</li>
))}
</ul>
<button onClick={() => dispatch(addToCart({ id: 3, name: 'Product 3', price: '$30' }))}>
Add Product 3
</button>
</div>
);
};
export default Cart;
Exercises
1. Exercise 1: Add a quantity property to each item in the cart and allow users to increase or
decrease the quantity.
2. Exercise 2: Create a wishlist feature using Redux, where users can add items to their wishlist.
3. Exercise 3: Implement a search feature to filter items in the cart based on the product name.
Conclusion
Redux is a powerful tool for managing state in large and complex applications. With its predictable
state transitions and centralized store, it makes debugging and state management more
straightforward. However, it is essential to evaluate if your application needs Redux before
Introduction to Redux
implementing it due to the added complexity and boilerplate.