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

114
Views
How can I pass an event parameter to an event listener declared in a useEffect in React?

I've found a handful of questions that ask of similar things, but none that satisfy all the criteria that I have to meet. I am trying to attach an event listener to the document within useEffect, then remove it with the useEffect return callback function. The problem lies in the fact that my listener function requires an event parameter to check which key was pressed.

import { useEffect } from 'react';

function Board() {
    useEffect(() => {
        document.addEventListener('keyup', commit);

        return () => {
            document.removeEventListener('keyup', commit);
        }
    }

    const commit = (event) => {
        if(event.target.keyCode === '13') {
            console.log('Enter key pressed');
        }
    }

    return (
        <div className="Board">
            This is my component
        </div>
    )
}

This will never console.log anything because there is no event variable being passed to the listener.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can access directly key from event object in eventHandler( commit fn) and pass a empty dependency array to useEffect

import { useEffect } from 'react';

function Board() {
    useEffect(() => {
        document.addEventListener('keyup', commit);

        return () => {
            document.removeEventListener('keyup', commit);
        }
    },[])

    const commit = (event) => {
        if(event.key === 'a') {
            console.log('Enter key pressed',event.key);
        }
    }

    return (
        <div className="Board">
            This is my component
        </div>
    )
}
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!