Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
implementing Local Storage in React useStateValue()

I want to be able to store items selected from my home page in Local Storage, as I'm using useStateValue().

The items display on the Checkout page correctly, however, on refreshing, the Checkout page becomes empty and returns to zero. The code below works fine with normal useState. I don't know what I am missing when using useStateValue().

My code:

import React from "react";
import "./Checkout.css";
import CheckoutProduct from "./CheckoutProduct";
import { useStateValue } from "./StateProvider";
import Subtotal from "./Subtotal";

function Checkout() {
  const [{ basket, user }, dispatch] = useStateValue();

  React.useEffect(() => {
    const data = localStorage.getItem("my-cart-list");
    if (data) {
      dispatch(JSON.parse(data))
    }
  }, []);

  React.useEffect(() => {
    localStorage.setItem("my-cart-list", JSON.stringify(basket))
  });
almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You forgot the dependency array, which means that the setItem will be called on every render:

React.useEffect(() => {
  localStorage.setItem("my-cart-list", JSON.stringify(basket))
});

If you want to call setItem when "basket" changes, you should use:

React.useEffect(() => {
  localStorage.setItem("my-cart-list", JSON.stringify(basket))
}, [basket]);
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!