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

200
Views
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 answers
Answer question

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 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!