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

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

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