Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

0

Use the refresh button and it will reflect the changes

enter image description here

about 4 years ago · Juan Pablo Isaza Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda