Skip to content

Instantly share code, notes, and snippets.

@pachun
Created April 13, 2023 16:45
Show Gist options
  • Save pachun/1a8c08c803b004bfd14f1f18d433cbac to your computer and use it in GitHub Desktop.
Save pachun/1a8c08c803b004bfd14f1f18d433cbac to your computer and use it in GitHub Desktop.
import { useRef } from "react"
const useRefsWithKeys = <T>(): {
setRefForKey: (key: string) => (element: T) => void
getRefForKey: (key: string) => T
} => {
const ref = useRef<Record<string, T>>({})
const setRefForKey =
(key: string) =>
(element: T): void => {
ref.current[key] = element
}
const getRefForKey = (key: string): T => {
return ref.current[key]
}
return {
setRefForKey,
getRefForKey,
}
}
export default useRefsWithKeys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment