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

63
Visualizações
useState does not rerender

I have a problem where useState updates the state but does not show the changes until I refresh the app. First, I declare an array called sampleFriends, made up of objects with fields "name", "location", and "picture" (each element of the array looks similar to: {name: 'John', location: 'Boston', picture: TestImage}).

Then, I have the following useState:

const [selectedFriends, setSelectedFriends] = useState([])

At some point, I successfully render

sampleFriends.map(({ name, location, image }, index) => (
<NewMsgTableRow
  name={name}
  index={index}
  location={location}
  image={image}
  onPress={() => selectFriend(name)}
/>

))

And I also have this function right above

  const selectFriend = name => {
    // if the friend is not already selected
    if (!selectedFriends.find(e => e === name)) {
      const newFriends = selectedFriends
      newFriends.push(name)
      setSelectedFriends(newFriends)
    }
  }

The component NewMsgTableRow has a button that uses onPress

  <TouchableOpacity
    onPress={onPress}
  >

So, I want to render selectedFriends as soon as they are selected (the TouchableOpacity is touched and thus the state updates). However, when I click the button, nothing shows up until I edit and save my code and it refreshes automatically. It was my understanding that useState rerendered the components as soon as it was updated, but it is not happening in this case and I can't figure out why. I've been reading that it is async and that it does not change it instantly, but I don't know how to make it work. Hope it makes sense and thanks for your help!!

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

0

You can use array spread or Array.concat() to make a shallow clone, and add new items as well) so change the line below:

const newFriends = selectedFriends

to this line :

const newFriends = [...selectedFriends]
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