Hook

useClickOutside

The useClickOutside hook detects clicks outside a specified element. It is ideal for closing dropdowns, modals, popovers, menus, and other interactive components.

Import
import { useClickOutside } from "@shivms/ui";

API

The hook returns a ref and executes a callback when a click occurs outside the referenced element.

ref

Attach the returned ref to the element you want to monitor.

handler

Callback executed whenever a click occurs outside the element.

Automatic Cleanup

Event listeners are removed automatically when the component unmounts.

Basic Usage

Attach the returned ref to your component and provide a callback that runs whenever the user clicks outside it.

import {
    useState,
} from "react";

import {
    useClickOutside,
} from "@shivms/ui";

export default function App() {
    const [open, setOpen] = useState(true);

    const ref = useClickOutside(() => {
        setOpen(false);
    });

    return (
        <div ref={ref}>
            {open && "Dropdown"}
        </div>
    );
}

Features

01

Close Overlays

Automatically close dropdowns, dialogs and popovers when users click elsewhere.

02

Easy Integration

Simply attach the returned ref to any HTML or React element.

03

Automatic Cleanup

Event listeners are cleaned up automatically to help avoid memory leaks.

Continue Reading

Explore more SHIVMS UI documentation and guides.