Skip to content

Commit

Permalink
Reduce useCallbackRef overhead
Browse files Browse the repository at this point in the history
  • Loading branch information
jassmith committed Feb 11, 2024
1 parent d2be6e6 commit 0f9b617
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions packages/core/src/data-editor/use-initial-scroll-offset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(initialValue: T, callback: (newVal: T) => void) {
const realRef = React.useRef<T>(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<T>(
initialValue: T | null,
callback: (newValue: T | null, lastValue: T | null) => void
): React.MutableRefObject<T | null> {
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(
Expand Down

0 comments on commit 0f9b617

Please sign in to comment.