Simplify and clean up your components with this react hooks collection.
before.tsx
import { useEffect, useState } from 'react';
export function Counter() {
const [counter, setCounter] = useState(0);
useEffect(() => {
function handleKeyPress(event) {
if (event.code === 'Space') {
setCount(prev => prev + 1);
}
}
window.addEventListener('keydown', handleKeyPress);
return () => {
window.removeEventListener('keydown', handleKeyPress);
};
}, []);
return <div>{count}</div>;
}
after.tsx
import { useCounter, useKeyboard } from 'react-pre-hooks';
export function Counter() {
const counter = useCounter();
useKeyboard({ keys: { 'space': () => counter.inc() }});
return <div>{counter.value}</div>;
}