useClickOutside
useClickOutside is a custom React hook that listens for clicks and touches outside of a referenced element and triggers a callback.
Usage
import { useClickOutside } from "hookify-react";
import { useState } from "react";
export default function ClickOutsideExample() {
const [isOpen, setIsOpen] = useState(true);
const { ref } = useClickOutside<HTMLDivElement>(() => setIsOpen(false));
return (
<div>
<button onClick={() => setIsOpen(true)}>Open Modal</button>
{isOpen && (
<div
ref={ref}
style={{ padding: "20px", border: "1px solid black", width: "200px" }}
>
Click outside of this box to close it.
</div>
)}
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callback | (event: MouseEvent | TouchEvent) => void | - | Function executed when a click or touch occurs outside the referenced element. |
Return Value
useClickOutside returns an object with the following properties:
| Property | Type | Description |
|---|---|---|
ref | React.MutableRefObject<T | null> | A ref to attach to the element you want to watch. |
Behavior
- Registers
mousedownandtouchstartlisteners ondocument. - Only fires the
callbackwhen the click/touch target is outside the referenced element. - Ignores events when the element is not yet mounted, and ignores clicks inside the element.
- Always calls the latest
callback. - Ideal for closing modals, dropdowns, or any UI that should dismiss on an outside click.
SSR Safety
useClickOutside is safe during server-side rendering. It resolves document only in the browser and registers listeners inside an effect.