Skip to main content

useEvent

Basic implementation of React RFC useEvent. It lets you define event handlers that can read the latest props/state but have always stable function identity

Usage

Live Editor

function Demo() {
  const [count, setCount] = useState(0);

  const callbackFn = useCallback(() => {
    alert(`Current count is ${count}`);
  }, [count]);

  const memoizedFn = useEvent(() => {
    alert(`Current count is ${count}`);
  });

  return (
    <>
      <p>count: {count}</p>
      <button
        type="button"
        onClick={() => {
          setCount(c => c + 1);
        }}
      >
        Add Count
      </button>
      <div style={{ marginTop: 16 }}>
        <button type="button" onClick={callbackFn}>
          call callbackFn
        </button>
        <button type="button" onClick={memoizedFn} style={{ marginLeft: 8 }}>
          call memoizedFn
        </button>
      </div>
    </>
  );
};

Result
Loading...

API

useEvent

Returns

T

Arguments

ArgumentDescriptionTypeDefaultValue
fnfunctionT (Required)-