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

111
Vistas
Not able to change the state with event handlers in React
const [isToSave, setisToSave] = React.useState(false)
const myStateRef = React.useRef(isToSave);
React.useEffect(() => {
    window.addEventListener('set-is-to-save', () => {
        setisToSave(!myStateRef.current)
    }, false);
    return () => {
        window.removeEventListener('set-is-to-save', () => {
            setisToSave(!myStateRef.current)
        });
    }
}, [])

function handleOnClick(e: React.MouseEvent<HTMLDivElement>): void {
    myStateRef.current=!isToSave
    setisToSave(myStateRef.current)
}

handleOnClick function is called by the onClick for one of the component and it seems to be working fine. But, whenever I try to change the state from independent components using event triggers, the state of isToSave doesn't change.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

For this simple usecase, you dont have to maintain state using useRef:

You can look at my quick test on my code that triggers a custom event here:

https://codesandbox.io/s/brave-https-4q6wd?file=/src/App.js

Basically if you use the state update with callback, it should work:

window.addEventListener('set-is-to-save', () => {
    setisToSave((val) => !val)
}, false);

P.S: Be careful with custom events and security. If the communication is within same application, you should be using context or other state management.

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