Search code examples
javascriptreactjsuse-statereact-state

Why does this method updates react state very slowly?


I have two components. Parent component: Board and child component Cell. I am rendering 9 Cells using a loop in the Board component.

This is the child component(Cell.js):

function Cell(props) {
    return <button style={style} className='cells' id={props.id} onClick={(e) => { props.handleclick(e) }}>{props.text}</button>;
}

This is the Parent component(Board.js):

function Board() {
    let [board, setBoard] = useState(['', '', '', '', '', '', '', '', '']);
    const handleClick = (e) => {
        let newBoard = [...board];
        newBoard[2] = "0";
        setBoard(newBoard);
    }
    return <div style={style}>
        {board.map((item, i) => {
            return <><Cell handleclick={handleClick} text={item} key={i} /></>
        })
        }
    </div>
}

This works perfectly but there is another method I tried where I made some changes in the handleClick method.

const handleClick = (e) => {
        let newBoard = board;
        newBoard[2] = "0";
        setBoard(newBoard);
    }

This takes too much time to change the state. State is getting changed that I have confirmed by looking at the react components in React Dev tools. What I am not able to understand it why this method takes too much time to update the state?


Solution

  • let newBoard = board;
    newBoard[2] = "0";
    setBoard(newBoard);
    

    You are mutating the state. When you set state in a function component, react does a === between the old and new state. Since it's the same array, react thinks nothing has changed, and so the component does not rerender. It might never render, though in your case it looks like some other component eventually sets state and causes a rerender.

    Instead, always create a new state:

    let newBoard = [...board];
    newBoard[2] = "0";
    setBoard(newBoard);