Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

62
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!