From 0f9b6172aabd072451276f51f16179d6bdbc8f8b Mon Sep 17 00:00:00 2001 From: Jason Smith Date: Sun, 11 Feb 2024 11:45:59 -0800 Subject: [PATCH] Reduce useCallbackRef overhead --- .../data-editor/use-initial-scroll-offset.ts | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/packages/core/src/data-editor/use-initial-scroll-offset.ts b/packages/core/src/data-editor/use-initial-scroll-offset.ts index 2affbdf1b..e3feaf05a 100644 --- a/packages/core/src/data-editor/use-initial-scroll-offset.ts +++ b/packages/core/src/data-editor/use-initial-scroll-offset.ts @@ -3,25 +3,32 @@ import type { VisibleRegion } from "./visible-region.js"; import type { DataEditorCoreProps } from "../index.js"; import { useStateWithReactiveInput } from "../common/utils.js"; -function useCallbackRef(initialValue: T, callback: (newVal: T) => void) { - const realRef = React.useRef(initialValue); - const cbRef = React.useRef(callback); - cbRef.current = callback; - - return React.useMemo( - () => ({ +// shamelessly stolen and modified from: https://github.com/theKashey/use-callback-ref +// MIT License https://github.com/theKashey/use-callback-ref/tree/master?tab=MIT-1-ov-file#readme +function useCallbackRef( + initialValue: T | null, + callback: (newValue: T | null, lastValue: T | null) => void +): React.MutableRefObject { + const [ref] = React.useState(() => ({ + value: initialValue, + callback, + facade: { get current() { - return realRef.current; + return ref.value; }, - set current(value: T) { - if (realRef.current !== value) { - realRef.current = value; - cbRef.current(value); + set current(value) { + const last = ref.value; + + if (last !== value) { + ref.value = value; + ref.callback(value, last); } }, - }), - [] - ); + }, + })); + ref.callback = callback; + + return ref.facade; } export function useInitialScrollOffset(