Day-17 React with Me
Understanding Redux Toolkit
Redux is a popular state management library for JavaScript applications, especially those built with React. However, setting up and managing a Redux application can sometimes be complex and verbose. To address this, Redux Toolkit was introduced as the official, recommended way to write Redux logic. It provides a set of tools and best practices to streamline and simplify the process of managing application state.
What is Redux Toolkit?
Redux Toolkit (RTK) is a set of tools and functions designed to simplify Redux development. It helps reduce boilerplate code, enforce best practices, and ensure that state management in your application is efficient and maintainable. RTK includes utilities for setting up the store, creating reducers, and managing asynchronous logic with a focus on reducing complexity.
Key Features of Redux Toolkit
ConfigureStore:
Simplifies store creation with good default settings.
Automatically combines reducers and adds middleware.
Configures the Redux DevTools Extension by default.
CreateSlice:
Simplifies the process of writing reducers and actions.
Allows defining a slice of the state, along with the reducer logic and action creators, in one place.
CreateAsyncThunk:
Provides a standardized way to handle asynchronous actions.
Automatically dispatches lifecycle actions (pending, fulfilled, rejected) based on promise states.
Immer Integration:
Allows writing immutable update logic using "mutating" syntax.
Automatically handles immutability under the hood, reducing boilerplate code.
Benefits of Redux Toolkit
Reduced Boilerplate: RTK minimizes the amount of code needed to set up Redux.
Improved Developer Experience: With tools like
createSlice
andcreateAsyncThunk
, developers can focus more on application logic than on Redux setup.Consistency: RTK enforces best practices, leading to more consistent codebases.
Built-in Immutability: The use of Immer ensures that state updates are done immutably without additional libraries or code.
How Redux Toolkit is utilized in our Foodie-Boodie App to manage state efficiently.
1. Setting Up Redux Toolkit
The first step in using Redux Toolkit is to set up the store. In the Foodie-Boodie App, the store configuration is handled in the appStore.js
file. This file imports the necessary functions from Redux Toolkit and creates a store with a slice reducer.
import { configureStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';
const appStore = configureStore({
reducer: {
cart: cartReducer,
},
});
export default appStore;
2. Creating Slices
Redux Toolkit introduces the concept of "slices." A slice represents a portion of the Redux state and includes the initial state, reducers, and actions. In the Foodie-Boodie App, there is a cartSlice.js
file that defines the cart slice.
import { createSlice } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState: {
items: [],
},
reducers: {
addItem: (state, action) => {
state.items.push(action.payload);
},
removeItem: (state, action) => {
state.items = state.items.filter(item => item.id !== action.payload.id);
},
},
});
export const { addItem, removeItem } = cartSlice.actions;
export default cartSlice.reducer;
3.Providing the Store
To make the Redux store available to the entire application, it needs to be provided at the top level of the component tree. This is done using the Provider
component from react-redux
, which is wrapped around the AppLayout
component in index.js
.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import appStore from './utils/appStore';
import AppLayout from './AppLayout';
ReactDOM.render(
<Provider store={appStore}>
<AppLayout />
</Provider>,
document.getElementById('root')
);
4. Connecting Components to the Store
To interact with the Redux store, components need to be connected to it. This is achieved using the useSelector
and useDispatch
hooks from react-redux
. In the Foodie-Boodie App, the Header
component uses useSelector
to access the number of items in the cart.
import React from 'react';
import { useSelector } from 'react-redux';
const Header = () => {
const cartItems = useSelector((store) => store.cart.items);
return (
<div className="header">
<div className="cart">
<i className="ri-shopping-cart-line"></i>
{cartItems.length}
</div>
</div>
);
};
export default Header;
Similarly, the useDispatch
hook is used to dispatch actions, such as adding or removing items from the cart. This is demonstrated in the MenuCard
component.
import React from 'react';
import { useDispatch } from 'react-redux';
import { addItem } from '../utils/cartSlice';
const MenuCard = ({ menuItem }) => {
const dispatch = useDispatch();
return (
<div className="menu-card">
<button
onClick={() => dispatch(addItem(menuItem))}
className="add-to-cart"
>
Add to Cart
</button>
</div>
);
};
export default MenuCard;
for reference - https://github.com/piyusss11/Foodie-Boodie-App-React