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

149
Visualizações
React useState is incrementing twice

I am building a simple form management with a history.

I replicated a simple version of it on codesandbox

import { useState } from "react";
import "./styles.css";

const sample = ["what", "who", "where"];
const sampleL = sample.length;

export default function App() {
    const [, indexSet] = useState([0, 0]);
    const [, historySet] = useState([]);
    const onClickNext = () => {
        indexSet((index) => {
            const [i] = index;
            let x = i + 1;
            // for loop used for some checks but in sample only runs once
            for (; x < sampleL; x++) {
                console.log("next > index", { index, i, x });
                historySet((history) => {
                    const ex = [...history, i];
                    console.log("next > history", { h: history, i, ex });
                    return ex;
                });
                return [x, 1];
            }
            return index;
        });
    };
    const onClickBack = () => {
        historySet((history) => {
            console.log("back > history", { h: history });
            if (history.length === 0) return history;
            const hx = [...history];
            indexSet([hx.pop(), -1]);
            return hx;
        });
    };
    return (
        <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
            <p>Open console, click next twice, click back once</p>
            <p>Why is history with three values instead of two?</p>
            <button onClick={onClickNext}>Next</button>
            <button onClick={onClickBack}>Back</button>
        </div>
    );
}
  1. Open the console
  2. Click the Next button - index becomes [1,1] and history becomes [0]
  3. Click the Next button - index becomes [2,1] and history becomes [0,1]
  4. Click the back button once - expect index to become [1,-1] and history to become [0]; Instead history becomes [0,1] from [0,1,1]. When, why, and how did it become [0,1,1]?

I kept the code as close to my original source. However, on my computer, the multiple runs of indexSet is recorded via console. On codesandbox, the array magically has an additional item. Both result with the same error.

Why is indexSet running twice, causing history to become [0,1,1]? Is this an error with React?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As per React, its expected behavior. https://github.com/facebook/react/issues/24057

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