包详细信息

use-latest-callback

satya1646.6mMIT0.2.4

React hook which returns the latest callback without changing the reference

react, use-event, use-callback

自述文件

use-latest-callback

React hook which returns the latest callback without changing the reference.

This is useful for scenarios such as event listeners where you may not want to resubscribe when the callback changes.

Installation

Open a Terminal in the project root and run:

npm install use-latest-callback

Usage

The useLatestCallback hook accepts a function as its argument and returns a function that preserves its reference across renders.

import useLatestCallback from 'use-latest-callback';

// ...

function MyComponent() {
  const callback = useLatestCallback((value) => {
    console.log('Changed', value);
  });

  React.useEffect(() => {
    someEvent.addListener(callback);

    return () => someEvent.removeListener(callback);
  }, [callback]);

  return <>{/* whatever */}</>;
}

It's important to note that the callback is not intended to be called during the render phase. Only call the callback in response to an event.

更新日志

0.2.3 (2024-11-14)

0.2.2 (2024-11-14)

0.2.1 (2024-07-10)

0.2.0 (2024-07-10)

Features

  • remove .default from commonjs output (80c3cb2)

0.1.11 (2024-07-07)

Bug Fixes

  • fix missing file in files field (2857de3)

0.1.10 (2024-07-07)

Bug Fixes

  • make the exports esm compatible (626d3fd)

0.1.9 (2023-11-09)

Bug Fixes

  • fix paths in package.json (13828a2)

0.1.8 (2023-11-09)