Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda