Files
starface-outlook-sync-addin/node_modules/@fluentui/react-hooks/lib/useEventCallback.js
T
Stefan Hacker 37ad745546 first commit
2026-04-03 09:38:48 +02:00

37 lines
1.7 KiB
JavaScript

import * as React from 'react';
import { useConst } from './useConst';
import { useIsomorphicLayoutEffect } from '@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
*/
export function useEventCallback(fn) {
var callbackRef = React.useRef(function () {
throw new Error('Cannot call an event handler while rendering');
});
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 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);
}; });
}
//# sourceMappingURL=useEventCallback.js.map