@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
53 lines • 2.19 kB
JavaScript
"use client";
/**
* Stable event callback: returns a function whose identity never changes but always
* invokes the latest `callback`. Avoids stale closures without re‑creating handlers.
*
* Why not `useCallback`? Its identity depends on a deps array:
* - omit deps -> stale; include deps -> new function each render.
* - This hook decouples identity from freshness.
*
* How it works: a single stable "trampoline" function delegates to a mutable ref. The current
* `callback` is promoted from `next` in an insertion/layout phase effect so abandoned concurrent
* renders cannot leak outdated handlers.
*
* Guarantees: stable identity; latest logic executed; no calls from uncommitted renders; dev
* error if invoked during render; safe when `callback` is undefined (no-op).
*/
import React, { useLayoutEffect } from "react";
import { useRefWithInit } from "./useRefWithInit.js";
/* https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379 */
const useInsertionEffect = React[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)];
const useSafeInsertionEffect =
// React 17 doesn't have useInsertionEffect.
useInsertionEffect &&
// Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
useInsertionEffect !== useLayoutEffect
? useInsertionEffect
: (fn) => fn();
/**
* TODO: Long term, replace `useCallbackRef` with this hook.
*/
export function useEventCallback(callback) {
const stable = useRefWithInit(createStableCallback).current;
stable.next = callback;
useSafeInsertionEffect(stable.effect);
return stable.trampoline;
}
function createStableCallback() {
const stable = {
next: undefined,
callback: assertNotCalled,
trampoline: (...args) => { var _a; return (_a = stable.callback) === null || _a === void 0 ? void 0 : _a.call(stable, ...args); },
effect: () => {
stable.callback = stable.next;
},
};
return stable;
}
function assertNotCalled() {
if (process.env.NODE_ENV !== "production") {
throw new Error("Aksel: Cannot call an event handler while rendering.");
}
}
//# sourceMappingURL=useEventCallback.js.map