Remove Items Dynamically from Your Cart with Recoil - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Monday, July 20, 2026

Remove Items Dynamically from Your Cart with Recoil

Remove Items Dynamically from Your Cart with Recoil

Screenshot from the tutorial
Screenshot from the tutorial

Remove Items Dynamically from Your Cart with Recoil

In this tutorial, we'll explore how to dynamically manage your shopping cart using Recoil, a state management library for React applications. We'll cover the fundamental concepts of Recoil, how to set up a cart, and how to remove items from it efficiently. Let’s dive in!

What is Recoil?

Recoil is a state management library for React that allows you to manage global state with ease. It provides a more straightforward API compared to other state management solutions and integrates seamlessly with React's concurrent features. With Recoil, you can create atoms (units of state) and selectors (functions that derive state) to manage your application's state effectively.

Setting Up Your Project

To get started, you need to have a React application. If you don't have one set up yet, you can create a new React app using Create React App:

npx create-react-app shopping-cart
cd shopping-cart

Next, install Recoil:

npm install recoil

Creating the Cart State with Atoms

First, we need to create an atom to represent our cart. An atom is a piece of state that can be read from and written to from any component.

Defining the Atom

Create a new file called cartAtom.js in the src directory and add the following code:

// src/cartAtom.js
import { atom } from 'recoil';

export const cartAtom = atom({
  key: 'cartAtom', // unique ID for this atom
  default: [],     // default value (initial state)
});

This atom, cartAtom, will hold an array of items in our cart.

Building the Cart Component

Now, let's create a Cart component that will display the items in the cart and allow users to remove them.

Creating the Cart Component

Create a new file called Cart.js:

// src/Cart.js
import React from 'react';
import { useRecoilState } from 'recoil';
import { cartAtom } from './cartAtom';

const Cart = () => {
  const [cart, setCart] = useRecoilState(cartAtom);

  const removeItem = (itemToRemove) => {
    setCart((prevCart) => prevCart.filter(item => item.id !== itemToRemove.id));
  };

  return (
    <div>
      <h2>Your Cart</h2>
      <ul>
        {cart.map(item => (
          <li key={item.id}>
            {item.name} 
            <button onClick={() => removeItem(item)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Cart;

Explanation

  1. useRecoilState: This hook is used to read and write the cart state.
  2. removeItem Function: This function filters out the item that the user wants to remove from the cart.
  3. Rendering the Cart: The items are mapped and displayed in a list, with a button to remove each item.

Adding Items to the Cart

To test our Cart component, we need a way to add items to it. Let's create a simple component for this purpose.

Creating the Add Item Component

Create a new file called AddItem.js:

// src/AddItem.js
import React, { useState } from 'react';
import { useRecoilState } from 'recoil';
import { cartAtom } from './cartAtom';

const AddItem = () => {
  const [cart, setCart] = useRecoilState(cartAtom);
  const [itemName, setItemName] = useState('');

  const addItem = () => {
    const newItem = { id: Date.now(), name: itemName };
    setCart([...cart, newItem]);
    setItemName('');
  };

  return (
    <div>
      <input 
        type="text" 
        value={itemName} 
        onChange={(e) => setItemName(e.target.value)} 
        placeholder="Enter item name"
      />
      <button onClick={addItem}>Add to Cart</button>
    </div>
  );
};

export default AddItem;

Explanation

  1. Input Field: An input field is used to enter the name of the item.
  2. addItem Function: This function creates a new item and updates the cart state with the new item.

Integrating Components

Finally, let’s integrate the AddItem and Cart components in our main App.js file.

// src/App.js
import React from 'react';
import { RecoilRoot } from 'recoil';
import AddItem from './AddItem';
import Cart from './Cart';

const App = () => {
  return (
    <RecoilRoot>
      <div>
        <h1>Shopping Cart</h1>
        <AddItem />
        <Cart />
      </div>
    </RecoilRoot>
  );
};

export default App;

Conclusion

In this tutorial, we learned how to set up a simple shopping cart using Recoil in a React application. We created an atom to manage the cart state and developed components to add and remove items dynamically.

With Recoil, managing global state becomes a breeze, allowing for a smoother user experience. Feel free to expand upon this example by adding features such as item quantities, total price calculation, or persistent cart storage using local storage.

Happy coding!

Another screenshot from the tutorial
Another view from the tutorial

Connect with SkillBakery Studios

Explore more tutorials, tools, and resources:

Posted by SkillBakery Studios

No comments:

Post a Comment

Post Top Ad