useClickAnyWhere()

This simple React hook offers you a click event listener at the page level, don't repeat yourself.

It is made on the useEventListener.

The Hook

1import { useEventListener } from '../useEventListener'
2
3type Handler = (event: MouseEvent) => void
4
5function useClickAnyWhere(handler: Handler) {
6 useEventListener('click', event => {
7 handler(event)
8 })
9}
10
11export default useClickAnyWhere

Usage

1import React, { useState } from 'react'
2
3import { useClickAnyWhere } from 'usehooks-ts'
4
5export default function Component() {
6 const [count, setCount] = useState(0)
7
8 useClickAnyWhere(() => {
9 setCount(prev => prev + 1)
10 })
11
12 return <p>Click count: {count}</p>
13}

Edit on CodeSandbox

See a way to make this page better?
Edit there »