useOnClickRef
Returns a ref that handles native click and touch-end events.
About
useOnClickRef attaches native click and touchend listeners to an element and calls one no-argument callback for either event.
Example
import { useState } from "react";
import { useOnClickRef } from "rooks";
export default function ClickCounter() {
const [count, setCount] = useState(0);
const clickRef = useOnClickRef(() => {
setCount((value) => value + 1);
});
return (
<button
ref={(node) => {
if (node) clickRef(node);
}}
>
Activations: {count}
</button>
);
}Parameters
onClick: a no-argument callback. The active native listeners call the latest version supplied during render.
Return value
The hook returns a callback ref for an HTMLElement.
Behavior and lifecycle
Both native handlers call preventDefault() before invoking the callback. The listeners are removed when the subscribed target is replaced or the component unmounts. The current implementation ignores the null value React sends when a ref is detached, so removing only the element while keeping the hook mounted can leave the old element subscribed until another target is assigned or the component unmounts. Some touch browsers may emit both touchend and a later click, which can produce two calls.
Compatibility and accessibility
Because default activation is prevented, check form submission and link navigation before using this hook on semantic controls. Prefer React's onClick when it is sufficient: it already covers keyboard activation for native buttons. This hook subscribes only in the browser.
Related
- useOnLongPress distinguishes a timed hold from release.
- useEventListenerRef attaches a chosen native event to an element.