UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

33 lines 1.23 kB
import { useMemo } from 'react'; import { useSyncedRef } from '../performance-optimization/useSyncedRef'; // Implementation export function useHookableRef(initialValue, onSet, onGet) { return useHookableRefFn(initialValue, onSet, onGet); } /** * Like `React.useRef` but it is possible to define get and set handlers * * @param initialValue Initial value of a hook. * @param onSet Function to be called while ref.current value set. Return value * will be stored in ref. * @param onGet Function to be called while ref.current value accessed. Return * value will be used as a return value. */ const useHookableRefFn = (initialValue, onSet, onGet) => { const onSetRef = useSyncedRef(onSet); const onGetRef = useSyncedRef(onGet); return useMemo(() => { let v = initialValue; return { get current() { return onGetRef.current === undefined ? v : onGetRef.current(v); }, set current(value) { v = onSetRef.current === undefined ? value : onSetRef.current(value); }, }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); }; //# sourceMappingURL=useHookableRef.js.map