@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
27 lines (20 loc) • 569 B
text/typescript
"use client";
import { useClientLayoutEffect } from "./useClientLayoutEffect";
import { useRefWithInit } from "./useRefWithInit";
export function useLatestRef<T>(value: T) {
const latest = useRefWithInit(createLatestRef, value).current!;
latest.next = value;
// eslint-disable-next-line react-hooks/exhaustive-deps
useClientLayoutEffect(latest.effect);
return latest;
}
function createLatestRef<T>(value: T) {
const latest = {
current: value,
next: value,
effect: () => {
latest.current = latest.next;
},
};
return latest;
}