Subscribe to events with a ref


use-event-listener adds given event listener to an element to which ref is assigned. Hook supports the same options as addEventListener method. After component is unmounted event listener is removed.

import { useState, useCallback } from 'react';
import { Button, Group } from '@mantine/core';
import { useEventListener } from '@mantine/hooks';
function Demo() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount((c) => c + 1), []);
const ref = useEventListener('click', increment);
return (
<Group position="center">
<Button ref={ref}>Button clicks: {count}</Button>


function useEventListener<K extends keyof HTMLElementEventMap, T extends HTMLElement = any>(
type: K,
listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): MutableRefObject<T>;
Build fully functional accessible web applications faster than ever
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback