UNPKG

@applicaster/zapp-react-native-utils

Version:

Applicaster Zapp React Native utilities package

25 lines (19 loc) 501 B
import React from "react"; type WithOptionalCleanup = { cleanup?: () => void; }; /** * returns a ref with an initial value that is lazily evaluated once * */ export const useRefWithInitialValue = <T>(initialValueGetter: () => T) => { const ref = React.useRef<T>(null); if (ref.current === null) { ref.current = initialValueGetter(); } React.useEffect(() => { return () => { (ref.current as unknown as WithOptionalCleanup)?.cleanup?.(); }; }, []); return ref; };