react-recipes
Version:
A React Hooks utility library containing popular customized hooks
39 lines (30 loc) • 856 B
Markdown
Adds an event listener
- `eventName: String`: Name of event. Required.
- `handler: Function`: Callback function. Required.
- `element?: Element`: Element to attach the eventListener, default is `window`.
```js
import { useEventListener } from "react-recipes";
function App() {
// State for storing mouse coordinates
const [coords, setCoords] = useState({ x: 0, y: 0 });
// Event handler utilizing useCallback ...
// ... so that reference never changes.
const handler = useCallback(
({ clientX, clientY }) => {
// Update coordinates
setCoords({ x: clientX, y: clientY });
},
[]
);
// Add event listener using our hook
useEventListener("mousemove", handler);
return (
<h1>
The mouse position is ({coords.x}, {coords.y})
</h1>
);
}
```