Skip to content

Instantly share code, notes, and snippets.

@faustienf
Created April 15, 2021 09:08
Show Gist options
  • Save faustienf/a62df4191c4e1e7c7e1804f44bca4e38 to your computer and use it in GitHub Desktop.
Save faustienf/a62df4191c4e1e7c7e1804f44bca4e38 to your computer and use it in GitHub Desktop.
import {
createRef,
useCallback,
useRef,
RefObject,
} from 'react';
type RefsMap<T> = Partial<Record<string, RefObject<T>>>;
type LinkRef<T> = (key: string) => RefObject<T>;
export const useRefsMap = (): [RefsMap<T>, LinkRef<T>] => {
const refsMap = useRef<RefsMap<T>>({});
const linkRef = useCallback(
(key: string) => {
if (!refsMap.current[key]) {
refsMap.current[key] = createRef<T>();
}
return refsMap.current[key] as RefsMap<T>;
},
[],
);
return [refsMap.current, linkRef];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment