Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda