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

190
Visualizações
React state hook 2D array first element is always empty

I have a 2d array, which I can push elements to. The issue i'm running into is the fact that when i print the contents, there is always a blank element at index 0. I do not know where this is coming from?

const [array, setArray] = useState([[]]);

// call this code 4 times

const updatedArray = [...array, ['test', 'test2']];
setArray(updatedArray);

enter image description here

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

0

The Problem here is

...array

since the initial value of the array is [].

So array[0] would be equal to [] and you append your new values beginning from array[1] on.

What you want to do is const updatedArray = [['test', 'test2']]; since you do not want the initial value to be kept.

about 4 years ago · Juan Pablo Isaza Relatório

0

Sometime this issue occurs with state.
In case of hooks, you should use useEffect hook, As below-

const [fruit, setFruit] = useState('');

useEffect(() => {
  console.log('Fruit', fruit);
}, [fruit])

This saved my day, Hope will help you too!!!

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