MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to useEventListener Hook with Explanation

ReactJS Hard Hooks & Effects 30 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around hook, react, useeventlistener. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Create a hook to attach an event listener safely.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use a ref for the handler and bind/unbind in an effect.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useEffect, useRef, useState } from 'react'; function useEventListener(target, type, handler) { const saved = useRef(handler); useEffect(() => { saved.current = handler; }, [handler]); useEffect(() => { if (!target) return; function listener(e) { saved.current(e); } target.addEventListener(type, listener); return () => target.removeEventListener(type, listener); }, [target, type]); } export default function App() { const [keys, setKeys] = useState([]); useEventListener(window, 'keydown', (e) => { setKeys((prev) => [e.key, ...prev].slice(0, 8)); }); return ( <div style={{ padding: 16 }}> <h2 style={{ marginTop: 0 }}>meetcode key log</h2> <div style={{ color: '#555' }}>Last keys: {keys.join(', ') || 'Press something'}</div> </div> ); }

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next