🛒 Persist Cart in Local Storage with Jotai | React State Management
Persist Cart in Local Storage with Jotai | React State Management
In modern web development, managing state effectively is essential for creating responsive and user-friendly applications. React, a popular JavaScript library, offers various tools for state management, with Jotai emerging as a lightweight and flexible solution. In this tutorial, we will explore how to persist a shopping cart in local storage using Jotai, allowing our application to maintain cart data even when the page is refreshed.
What is Jotai?
Jotai is a minimalistic state management library for React that emphasizes atomic state management. It allows developers to create state atoms, which can be used to manage state in a simple and efficient manner. Jotai is particularly well-suited for applications that require minimal boilerplate and straightforward state management solutions.
Why Persist State?
Persisting state, especially for a shopping cart, enhances the user experience by ensuring that users do not lose their selections when they navigate away from the page or refresh it. Using local storage allows us to save the cart data on the user's device, making it accessible across sessions.
Setting Up the Project
To get started, you'll need to set up a new React project. If you haven't done so already, you can create a new project using Create React App:
npx create-react-app my-cart-app
cd my-cart-app
Once your project is created, you will need to install Jotai:
npm install jotai
Creating the Cart Atom
First, let's create an atom for our cart. An atom is a piece of state in Jotai. We'll define an atom to hold our cart items.
Create a file called cartAtom.js in the src directory:
// src/cartAtom.js
import { atom } from 'jotai';
export const cartAtom = atom([]);
This simple atom will hold an array of cart items.
Persisting Cart Data in Local Storage
Now, we need to implement functionality to store the cart data in local storage. We'll create a function to load the cart from local storage when the app initializes and a function to save the cart to local storage whenever it changes.
In the cartAtom.js, add the following code:
// src/cartAtom.js
import { atom } from 'jotai';
const loadCartFromLocalStorage = () => {
const storedCart = localStorage.getItem('cart');
return storedCart ? JSON.parse(storedCart) : [];
};
const saveCartToLocalStorage = (cart) => {
localStorage.setItem('cart', JSON.stringify(cart));
};
export const cartAtom = atom(loadCartFromLocalStorage());
cartAtom.onMount = (setAtom) => {
const savedCart = loadCartFromLocalStorage();
setAtom(savedCart);
// Subscribe to local storage changes
const handleStorageChange = () => {
const updatedCart = loadCartFromLocalStorage();
setAtom(updatedCart);
};
window.addEventListener('storage', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
};
};
Explanation
- Load Cart: The
loadCartFromLocalStoragefunction retrieves the cart data from local storage and parses it. If no data is found, it returns an empty array. - Save Cart: The
saveCartToLocalStoragefunction saves the current state of the cart to local storage in string format. - Atom Initialization: The atom is initialized with the cart data from local storage.
- Event Listener: We listen to storage events to automatically update the cart if changes occur in another tab.
Creating the Cart Component
Now, let's create a simple cart component to demonstrate how to use our cartAtom. Create a new file called Cart.js:
// src/Cart.js
import React from 'react';
import { useAtom } from 'jotai';
import { cartAtom } from './cartAtom';
const Cart = () => {
const [cart, setCart] = useAtom(cartAtom);
const addItem = (item) => {
const newCart = [...cart, item];
setCart(newCart);
saveCartToLocalStorage(newCart);
};
const removeItem = (itemToRemove) => {
const newCart = cart.filter(item => item !== itemToRemove);
setCart(newCart);
saveCartToLocalStorage(newCart);
};
return (
<div>
<h2>Shopping Cart</h2>
<ul>
{cart.map((item, index) => (
<li key={index}>
{item}
<button onClick={() => removeItem(item)}>Remove</button>
</li>
))}
</ul>
<button onClick={() => addItem(`Item ${cart.length + 1}`)}>Add Item</button>
</div>
);
};
export default Cart;
Explanation
- Add Item: The
addItemfunction adds a new item to the cart and updates local storage. - Remove Item: The
removeItemfunction removes an item from the cart and updates local storage. - Rendering the Cart: The cart is rendered as a list, displaying each item along with a button to remove it.
Integrating the Cart Component
Now, integrate the Cart component into the main application file, App.js:
// src/App.js
import React from 'react';
import Cart from './Cart';
const App = () => {
return (
<div>
<h1>My Shopping Cart</h1>
<Cart />
</div>
);
};
export default App;
Conclusion
In this tutorial, we explored how to persist a shopping cart in local storage using Jotai for state management in a React application. By leveraging the simplicity of Jotai and the power of local storage, we created a resilient shopping cart experience for users.
This approach not only enhances user experience but also demonstrates the effectiveness of atomic state management. Feel free to expand upon this example by adding features like total price calculation, product details, or even integration with an API.
Additional Resources
Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment