DEV Community

Cover image for Redux and Redux Toolkit
Melih Şahin
Melih Şahin

Posted on

Redux and Redux Toolkit

Redux
is a state management library for JavaScript applications. It provides a predictable state container that helps manage the state of an application in a consistent and centralized way. Redux is commonly used with React to build complex applications.

Redux Toolkit is a library that simplifies the use of Redux by providing a set of tools and guidelines. It allows developers to write less boilerplate code and focus on the application logic. Redux Toolkit includes features such as creating Redux slices, configuring a Redux store, and writing asynchronous actions.

Let's take a look at an example project that uses Redux Toolkit to build a shopping cart application. We'll start by creating a Redux slice for the cart.

import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState: {
    products: [],
    totalPrice: 0,
  },
  reducers: {
    addProduct: (state, action) => {
      state.products.push(action.payload);
      state.totalPrice += action.payload.price;
    },
    removeProduct: (state, action) => {
      const index = state.products.findIndex(product => product.id === action.payload);
      if (index !== -1) {
        state.totalPrice -= state.products[index].price;
        state.products.splice(index, 1);
      }
    },
  },
});

export const { addProduct, removeProduct } = cartSlice.actions;
export default cartSlice.reducer;
Enter fullscreen mode Exit fullscreen mode

In the above code, we use the createSlice function from Redux Toolkit to create a slice for the cart. The initialState object defines the initial state of the cart, which includes an empty array of products and a totalPrice of zero. The reducers object defines the actions that can be performed on the cart state. In this case, we define addProduct and removeProduct actions that modify the products array and update the totalPrice accordingly.

Next, we'll configure a Redux store using the configureStore function from Redux Toolkit.

import { configureStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';

const store = configureStore({
  reducer: {
    cart: cartReducer,
  },
});

export default store;

Enter fullscreen mode Exit fullscreen mode

In the above code, we use configureStore to create a Redux store and pass it the cartReducer we defined earlier. This creates a single source of truth for the cart state that can be accessed by any component in our application.

Finally, we'll create a React component that uses the cart state and actions to display and modify the contents of the cart.


import { useSelector, useDispatch } from 'react-redux'
import { addProduct, removeProduct } from './cartSlice'

function Cart() {
  const products = useSelector((state) => state.cart.products)
  const totalPrice = useSelector((state) => state.cart.totalPrice)
  const dispatch = useDispatch()

  const handleAddProduct = (product) => {
    dispatch(addProduct(product))
  }

  const handleRemoveProduct = (productId) => {
    dispatch(removeProduct(productId))
  }

  return (
    <div>
      <h1>Shopping Cart</h1>
      <button
        onClick={() => handleAddProduct({ id: 1, name: 'Product 1', price: 10 })}>
        Add Product
      </button>
      {products.length === 0 ? (
        <p>No products in cart</p>
      ) : (
        <ul>
          {products.map((product) => (
            <li key={product.id}>
              {product.name} - ${product.price}
              <button onClick={() => handleRemoveProduct(product.id)}>Remove</button>
            </li>
          ))}
        </ul>
      )}
      <p>Total Price: ${totalPrice}</p>
    </div>
  )
}

export default Cart
Enter fullscreen mode Exit fullscreen mode

In the above code, we use the useSelector hook to access the cart state and the useDispatch hook to dispatch actions to modify the cart state. We define handleAddProduct and handleRemoveProduct functions that dispatch the addProduct and removeProduct actions respectively. Finally, we render the contents of the cart using the products array and totalPrice value.

This is just a simple example of how Redux and Redux Toolkit can be used to manage the state of a React application. By using Redux Toolkit, we can write less boilerplate code and focus on the application logic, while still benefitting from the power and predictability of Redux.

Source:

Top comments (0)