SILENT
SILENT

Reputation: 4268

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?

Upvotes: 1

Views: 280

Answers (1)

SILENT
SILENT

Reputation: 4268

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

Upvotes: 2

Related Questions