Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my react component does not rerender when 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading