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

148
Views
How do I make windows event listener trigger once per keypress?

I currently have a react component and I am trying to have a windows event listener that triggers on each keydown and will react if it is the tab key, but currently it is hitting multiple times each time

Is there anyway to make it so each keydown is trigger once only? Here is the code

render() {
    window.addEventListener('keydown',(event) => {
         // here the eventListener should only trigger once per keypress, but it's hitting 4 times
         console.log("event",event);
    })
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

addEventListener does not belong into the render() function. There it will create a new event listener on every rerender of that component.

Instead, put it into componentDidMount lifecycle hook.

class Component extends React.Component{

  handleKeyDown =(event) =>{
    // here the eventListener should only trigger once per keypress, but it's hitting 4 times
    console.log("event",event);
  }
  componentDidMount(){
   window.addEventListener('keydown',this.handleKeyDown)
  }
  componentWillUnmount(){
    window.removeEventListener('keydown',this.handleKeyDown)
  }
  render() {
    return <button onClick={()=>this.setState((state)=>({test:state?.test+1}))}>test</button>
  }
}

Keep in mind, setting an event listener on window will create a global event listener. You should remove it, when you don't need it anymore, e.g. on componentWillUnmount

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!