Skip to main content

useEventListener

Description#

Suppose you would like to track the mouse position. You could subscribe to mouse move events like this:

Old implementation (click to expand)
import { useEffect, useState } from 'react';
const useMouseMove = () => {  const [coords, setCoords] = useState<[number, number]>([0, 0]);
  useEffect(() => {    const handler = ({ clientX, clientY }) => {      setCoords([clientX, clientY]);    };    window.addEventListener('mousemove', handler);    return () => {      window.removeEventListener('mousemove', handler);    };  }, []);
  return coords;};
export default useMouseMove;

We have written our own useEffect to manage the events. But this could be repetitive and tedious to do.

useEventListener abstracts this away: you only need to care about the event name and the handler function.

Usage#

import { useEventListener } from '@springtree/eva-suite-react-hooks';
const useMouseMove = () => {  const [coords, setCoords] = useState([0, 0]);
  useEventListener('mousemove', ({ clientX, clientY }) => {    setCoords([clientX, clientY]);  });
  return coords;};
export default useMouseMove;

References#