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

143
Views
Why my React component does not rerender when Set state was changed?

Can't get where is the problem hiding. I'm changing state but the component not rerender. So this is my code:

export const InterestsPupup: React.FC = ({interests, title, buttonText}) => {
  const [activeItems, setActiveItems] = useState(new Set())

  const clickOnItemHandler = (item: string) => {
    let newSet = activeItems
    activeItems.has(item) ? newSet.delete(item) : newSet.add(item)
    setActiveItems(prev => newSet)
  }

  return (
        <div className={styles.Container__main}>
            {interests.map((item , index) => {
              return (
                <div
                  key={index}
                  className={activeItems.has(item) ? clsx(styles.item, styles.item_active) : styles.item}
                  onClick={() => clickOnItemHandler(item)}
                >{item}</div>
              )
            })}
        </div>
  );
};

There is my state in shape of Set, i'm changing that state and nothing is happens, only after i reopen that popup component. So my state changes but the component doesn't rerender

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You're changing your state in place, you need to ensure you are passing in a new set object and not the same set object reference. Although you've modified the set, you're still passing through the same set object:

setActiveItems(currSet => {
  const newSet = new Set(currSet);
  if(newSet.has(item))
    newSet.delete(item);
  else
    newSet.add(item);
  return newSet;
});

I've replaced the ternary with an if-statement. The conditional operator ? : is generally used when you want to use the value that it returns, however, in your case the value isn't being used, so an if-statement is more appropriate.

about 4 years ago · Juan Pablo Isaza Report

0

You should write like this:

setActiveItems(newSet);
about 4 years ago · Juan Pablo Isaza Report

0

Someone just wrote a comment that helped and deleted it right after, but thank you The answer was: I just had to change this

let newSet = activeItems

On this:

let newSet = new Set([...activeItems])
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!