Today, we studied Redux Toolkit, a powerful tool to manage global state in React applications efficiently. Below is a summary of the steps we followed and concepts we covered.
Start by creating a new React project using create-react-app
or your preferred method.
npx create-react-app redux-toolkit-demo
cd redux-toolkit-demo
-
Install Redux Toolkit and React-Redux:
npm install @reduxjs/toolkit react-redux
-
Create a new folder named
store
in thesrc
directory. -
Inside
store
, create a filestore.js
and initialize the Redux store.import { configureStore } from '@reduxjs/toolkit'; import productReducer from './slices/productSlice'; const store = configureStore({ reducer: { products: productReducer, }, }); export default store;
In index.js
, wrap your app with the Provider
from react-redux
and pass the store to it.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store/store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
- Create a new folder called
slices
in thestore
directory. - Inside
slices
, create a file namedproductSlice.js
. - Define the initial state and reducers using
createSlice
from Redux Toolkit.
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
addedProducts: [], // Array to store product data
};
const productSlice = createSlice({
name: 'products',
initialState,
reducers: {
// Action to add a product
addProduct: (state, action) => {
state.addedProducts.push(action.payload);
},
// Action to delete a product by ID
deleteProduct: (state, action) => {
state.addedProducts = state.addedProducts.filter(
(product) => product.id !== action.payload
);
},
},
});
// Export actions and reducer
export const { addProduct, deleteProduct } = productSlice.actions;
export default productSlice.reducer;
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addProduct } from '../store/slices/productSlice';
const AddProduct = () => {
const [product, setProduct] = useState({ id: '', name: '' });
const dispatch = useDispatch();
const handleAddProduct = () => {
if (product.id && product.name) {
dispatch(addProduct(product));
setProduct({ id: '', name: '' });
}
};
return (
<div>
<input
type="text"
placeholder="Product ID"
value={product.id}
onChange={(e) => setProduct({ ...product, id: e.target.value })}
/>
<input
type="text"
placeholder="Product Name"
value={product.name}
onChange={(e) => setProduct({ ...product, name: e.target.value })}
/>
<button onClick={handleAddProduct}>Add Product</button>
</div>
);
};
export default AddProduct;
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { deleteProduct } from '../store/slices/productSlice';
const ProductList = () => {
const products = useSelector((state) => state.products.addedProducts);
const dispatch = useDispatch();
return (
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name}{' '}
<button onClick={() => dispatch(deleteProduct(product.id))}>
Delete
</button>
</li>
))}
</ul>
);
};
export default ProductList;
import React from 'react';
import AddProduct from './components/AddProduct';
import ProductList from './components/ProductList';
const App = () => {
return (
<div>
<h1>Redux Toolkit Demo</h1>
<AddProduct />
<ProductList />
</div>
);
};
export default App;
- Redux Toolkit Simplifies Redux:
- Combines reducers, actions, and initial state in one
createSlice
function.
- Combines reducers, actions, and initial state in one
- Global State Management:
- Easily manage application-wide state using a centralized store.
- Modular Code:
- Organized slices for better code readability and scalability.
- Configure a store using
configureStore
. - Define state and actions using
createSlice
. - Use
useDispatch
to trigger actions anduseSelector
to access state.
Happy Coding! 🚀