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

90
Views
Adding a new item to list in ReactJS functional Component not updating UI

I have a list as follows

const[users,setUsers]=useState([]);

to dynamically add a new user and update the UI i have a function as below

const addNewUser = newUser => {
      setUsers(previousUsers=>{
            //only add user if he has not been added
            let existingUser = previousUsers.find((x)=>x.id===newUser.id);
            if(!existingUser){
                previousUsers.push(newUser);
            }
            return previousUsers;
        });
}

Unfortunately the above code is not updating the UI. This is weird.

What could I be doing wrong?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I would do the check outside of the set state:

function addNewUser(newUser) {
  const existingUser = users.find(user => user.id === newUser.id);
  if (!existingUser) {
    setUsers(prev => ([...prev, newUser]));
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

The reason that the UI is not re-rendering is because state value is not changed. If you want to use arrays or objects in React State, you have to create a copy of the value before modifying it. You can find the basic example of doing it below:

const [todos, setTodos] = useState([]);
const handleAdd = (todo) => {
    const newTodos = [...todos];
    newTodos.push(todo);
    setTodos(newTodos);
}
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!