import { useState, useEffect } from 'react';

function useWindowKeyPress(targetKey) {
    const [keyPressed, setKeyPressed] = useState(false);
    function downHandler(event) {
        const { code } = event;
        if (code === targetKey) {
            setKeyPressed(true);
        }
    }
    const upHandler = (event) => {
        const { code } = event;
        if (code === targetKey) {
            setKeyPressed(false);
        }
    };
    useEffect(() => {
        window.addEventListener('keydown', downHandler);
        window.addEventListener('keyup', upHandler);
        return () => {
            window.removeEventListener('keydown', downHandler);
            window.removeEventListener('keyup', upHandler);
        };
    }, [downHandler, upHandler]);
    return keyPressed;
}

export { useWindowKeyPress };
