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

103
Vistas
React State does not update on first click

I was trying to build a simple data displaying system with two sorting buttons (ascending & descending).

The way I did it was fetch & display data from array using map method. Then in another component file I use useEffect to trigger the sorting.

The problem is the system doesn't rerenders instantly when I first click the button. The system will only rerenders on the second time I click the button (and showing result of first click).

Fetch data:

useEffect(() => {
 fetchData();
},[])

const fetchData = () => {
 SetItems(data.items)
}

Iterate data

<div>
    {items.map((item)=>
   <Details key={item.slug} item={item} />)}
</div>

Inside the Details component,

useEffect(() => {
 if(category==='ascending'){
 const sorted = items.sort((a,b) => a.time > b.time ? 1 : -1);
 setItems(sorted);}

 if(category==='descending'){
 const sorted = items.sort((a,b) => a.time < b.time ? 1 : -1);
 setItems(sorted);}

},[category])

assign sorted data to items, useEffect should re-renders every time the category is changed.

<button onClick={()=>setCategory('ascending') />
<button onClick={()=>setCategory('descending') />

When I click on a button, the system will not rerenders, the state will only renders after I click on the second button. For example:

  1. Click 'Ascending Button' -> Nothing changes.
  2. Click 'Descending Button' -> Data sorted by Ascending Order.
  3. Click 'Ascending Button' -> Data sorted by Descending Order.

*But the data shows correctly using console.log

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

sort() 'returns the reference to the same array', meaning when after sorting and updating your state, it checks and see's its still referencing the same array, and will not rerender. You need to copy the array when setting its state

useEffect(() => {
 if(category==='ascending'){
 const sorted = items.sort((a,b) => a.time > b.time ? 1 : -1);
 setItems([...sorted]);}

 if(category==='descending'){
 const sorted = items.sort((a,b) => a.time < b.time ? 1 : -1);
 setItems([...sorted]);}

},[category])
about 4 years ago · Santiago Gelvez 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