Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!