import { useState } from "react"; type MutableRefObjectWithLiving = ((newValue: T) => void) & { current: T; readonly living: T }; /** * This hook resembles the original `useRef` hook, but it also provides `living` property that contains a last non-null value of a ref. * @param initialValue - initial value of the ref */ export function useLivingRef(initialValue: T | null): MutableRefObjectWithLiving { const [ref] = useState(() => { let value: T | null = initialValue; let living: T | null = value; // @ts-expect-error Can't help TypeScript here const myRef: MutableRefObjectWithLiving = (newValue: T) => { myRef.current = newValue; }; Object.defineProperty(myRef, "current", { get: () => value, set: (newValue) => { value = newValue; if (newValue !== null) { living = newValue; } }, enumerable: true, }); Object.defineProperty(myRef, "living", { get: () => living, enumerable: true, }); return myRef; }); return ref; }