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

117
Visualizações
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?

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

0

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);
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