Skip to content
  • Sponsor
  • Notifications You must be signed in to change notification settings
  • Fork 3.2k

Files

Latest commit

d3d5bc9 Β· Jul 17, 2019

History

History
40 lines (29 loc) Β· 677 Bytes

useEvent.md

File metadata and controls

40 lines (29 loc) Β· 677 Bytes

useEvent

React sensor hook that subscribes a handler to events.

Usage

import {useEvent, useList} from 'react-use';

const Demo = () => {
  const [list, {push, clear}] = useList();

  const onKeyDown = useCallback(({key}) => {
    if (key === 'r') clear();
    push(key);
  }, []);

  useEvent('keydown', onKeyDown);

  return (
    <div>
      <p>
        Press some keys on your keyboard, <code style={{color: 'tomato'}}>r</code> key resets the list
      </p>
      <pre>
        {JSON.stringify(list, null, 4)}
      </pre>
    </div>
  );
};

Examples

useEvent('keydown', handler)
useEvent('scroll', handler, window, {capture: true})