Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

You should write like this:

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda