use-event-listener

Subscribe to events with a ref
Import

Usage

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>
</Group>
);
}

Definition

function useEventListener<K extends keyof HTMLElementEventMap, T extends HTMLElement = any>(
type: K,
listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): MutableRefObject<T>;