@carbon/react
Version:
React components for the Carbon Design System
30 lines (25 loc) • 988 B
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
;
var React = require('react');
/**
* Returns a stable callback reference that always points to the latest version
* of a callback. This is useful when you want to avoid including the callback
* in dependency arrays while still ensuring the latest callback implementation
* is used.
*
* @param callback - The callback to track.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/carbon-design-system/carbon/issues/20452
const useSavedCallback = callback => {
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
return React.useCallback((...args) => savedCallback.current ? savedCallback.current(...args) : undefined, []);
};
exports.useSavedCallback = useSavedCallback;