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

205
Vistas
React useState hook doesn't work as expected

I have a simple useState hook with which the state of selected checkboxes is managed.

The selected checkboxes should be displayed in the ui (within my filter).

The selected checkboxes are stored correctly, but only displayed when I close my filter component and open it again. Not immediately after a checkbox is checked.

Here is my current state (simplified):

Filter Component:

  const [selected, setSelected] = useState([]);

  const handleState = (id: string) => {
    const selectedIndex = selected.findIndex((i) => i.id === id);

    if (selectedIndex > -1) {
      selected.splice(checkedIndex, 1);
    } else {
      selected.push(data.find((i) => i.id === id)); 
    }

    // set the state of the selected checkboxes
    setSelected(selected);
  };  

Rendering:

  {selected.length > 0 ? (
     <div className="selected-boxes">
       {selected.map((cb) => (
         <span key={cb.label}>{cb.label}</span>
       ))}
     </div>
   ) : (
   // some other stuff
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

selected is an array that you mutate when some checkbox is checked but referentially this is still the same value so React won't rerender the component.

When you close the filter the component is unmounted and when you open it again it is mounted with the fresh values.

You need to return a new array instead of mutating the current one, for example like this:

// set the state of the selected checkboxes
    setSelected(selected.slice());

or

// set the state of the selected checkboxes
    setSelected([...selected]);

or use immer that allows you to work with immutable state in a more convenient way.

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