React: Modal Component Not Closing on Escape Key Press - Refactor with useEffect
I've searched everywhere and can't find a clear answer. I've searched everywhere and can't find a clear answer... I have a modal component that should close when the user presses the Escape key. However, after refactoring my component to use hooks, the key event listener seems to be not working properly. The modal opens correctly, but pressing the Escape key does nothing. I have tried adding the event listener in a `useEffect` hook, but it still doesn't close the modal. Here's a simplified version of my component: ```javascript import React, { useEffect } from 'react'; const Modal = ({ isOpen, onClose }) => { useEffect(() => { const handleKeyDown = (event) => { if (event.key === 'Escape') { onClose(); } }; if (isOpen) { window.addEventListener('keydown', handleKeyDown); } return () => { window.removeEventListener('keydown', handleKeyDown); }; }, [isOpen, onClose]); if (!isOpen) return null; return ( <div className="modal"> <h2>Modal Title</h2> <button onClick={onClose}>Close</button> </div> ); }; export default Modal; ``` I'm using React 18, and I noticed that the `onClose` prop is correctly passed down from the parent component, which also handles the modal's open state. I have also tried logging to the console inside the `handleKeyDown` function, but it never logs when pressing Escape. Am I missing something in my hook setup? Why isn't the event listener working as expected? Any pointers in the right direction?