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

143
Visualizações
Update 2d array using React and hooks useState and useEffect

I'm trying to create easy bouncing ball game in 2d array with React hooks. I have a problem to solve:

When the ball hits the green field, it should change the vector to random and change its value in the array from "Y" to "0". It changes direction, but the green space does not disappear from the board. It's still back after re-render.

Here's a full code: https://stackblitz.com/edit/react-cvlqsp?file=src/App.js

Edit

I found that the green box disappears, but each time the ball moves, it re-renders and it looks like it permanently. I can't help myself not to render the whole thing every time but only the ball movement. Should I use this in useEffect? and how?

Here's functions for random vector and value of array changes not working:

let random = () => {
    if (Math.random() < 0.5) {
      setVectorX((vectorX *= -1));
    } else {
      setVectorY((vectorY *= -1));
    }
  };

  let checkforYCollsion = () => {
    if (board[positionY][positionX] === 'Y') {
      random();
      board[positionY][positionX] = '0'
      
    }
  };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to update the state with the changed 2d array by calling setBoardToDisplay, not by assigning the value of board, since this will not trigger a re-render. You can do this by utilising a callback function in setBoardToDisplay.

setBoardToDisplay((prev) => {
  // make desired changes to prev and return it
})
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