UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

28 lines (27 loc) 1.04 kB
import { useMemo } from 'react'; import { useSyncedRef } from "../useSyncedRef/useSyncedRef.js"; /** * 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. */ export function useHookableRef(initialValue, onSet, onGet) { var onSetRef = useSyncedRef(onSet); var onGetRef = useSyncedRef(onGet); return useMemo(function () { var v = initialValue; return { get current() { return typeof onGetRef.current !== 'undefined' ? onGetRef.current(v) : v; }, set current(val) { v = typeof onSetRef.current !== 'undefined' ? onSetRef.current(val) : val; }, }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); }