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

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

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 Relatório

0

You should write like this:

setActiveItems(newSet);
about 4 years ago · Juan Pablo Isaza Relatório

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