Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
LocalStorage not updated with the latest value

I am new to react and I am experimenting with incrementing a value and storing it into local storage. I was able to write down the following code bellow, however, the last instance of the incremented number is not updated the local storage value. For example, if I press "+1" twice and the number is 10, the dom is updated twice and shows the number 12, but the value stored on local storage is 11. Why is this happening?

import { useState } from 'react'


function About () {

    const localStorageValue = parseInt(localStorage.getItem('value'))
    const [value, setValue] = useState(localStorageValue);

    function remove() {
        setValue((add) => add - 1)
        localStorage.setItem('value', parseInt(value))
    }

    function add() {
        setValue((add) => add + 1)
        localStorage.setItem('value', parseInt(value))
    }


    return (
        <>
            <h1>About page</h1>

            <button onClick={remove}>-1</button>
            {value}
            <button onClick={add}>+1</button>
        </>
    )
}

export default About;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use the refresh button and it will reflect the changes

enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar

0

Issue here is asynchronous behaviour of setState i.e. it will update the state value with a bit of delay and without stopping for complete execution of setState it will proceed to next line of code i.e. localStorage.setItem().

In your case setState is setValue

So to overcome this you can need some kind of callback function behaviour to achieve this with useState hook so you can use useEffect for the same as follows:

import { useState, useEffect } from "react";

function About() {
    const localStorageValue = parseInt(localStorage.getItem("value"));
    const [value, setValue] = useState(localStorageValue);

    useEffect(() => {
        localStorage.setItem("value", parseInt(value));
    }, [value]); // only rerun if value changes

    function remove() {
        setValue((add) => add - 1);
    }

    function add() {
        setValue((add) => add + 1);
    }

    return (
        <>
            <h1>About page</h1>

            <button onClick={remove}>-1</button>
            {value}
            <button onClick={add}>+1</button>
        </>
    );
}

export default About;

This will ensure that it will run everytime after successive state update.

PS. There's no need to use parseInt while storing as it will be stored as string only.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda