41 lines
1.9 KiB
JavaScript
41 lines
1.9 KiB
JavaScript
|
"use strict";
|
||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||
|
exports.useEventCallback = void 0;
|
||
|
var React = require("react");
|
||
|
var useConst_1 = require("./useConst");
|
||
|
var utilities_1 = require("@fluentui/utilities");
|
||
|
/**
|
||
|
* Modified `useCallback` that returns the same function reference every time, but internally calls
|
||
|
* the most-recently passed callback implementation. Can be useful in situations such as:
|
||
|
* - Event handler dependencies change too frequently, such as user props which might change on
|
||
|
* every render, or volatile values such as useState/useDispatch
|
||
|
* - Callback must be referenced in a captured context (such as a window event handler or unmount
|
||
|
* handler that's registered once) but needs access to the latest props
|
||
|
*
|
||
|
* In general, prefer `useCallback` unless you've encountered one of the problems above.
|
||
|
*
|
||
|
* https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
|
||
|
*
|
||
|
* @param fn - The callback function that will be used
|
||
|
* @returns A function which is referentially stable but internally calls the most recently passed callback
|
||
|
*/
|
||
|
function useEventCallback(fn) {
|
||
|
var callbackRef = React.useRef(function () {
|
||
|
throw new Error('Cannot call an event handler while rendering');
|
||
|
});
|
||
|
(0, utilities_1.useIsomorphicLayoutEffect)(function () {
|
||
|
callbackRef.current = fn;
|
||
|
}, [fn]);
|
||
|
// useConst rather than useCallback to ensure the reference is always stable
|
||
|
// (useCallback's deps list is an optimization, not a guarantee)
|
||
|
return (0, useConst_1.useConst)(function () { return function () {
|
||
|
var args = [];
|
||
|
for (var _i = 0; _i < arguments.length; _i++) {
|
||
|
args[_i] = arguments[_i];
|
||
|
}
|
||
|
var callback = callbackRef.current;
|
||
|
return callback.apply(void 0, args);
|
||
|
}; });
|
||
|
}
|
||
|
exports.useEventCallback = useEventCallback;
|
||
|
//# sourceMappingURL=useEventCallback.js.map
|