useUniqueId.ts 465 B

1234567891011121314151617
  1. import { uniqueId } from 'lodash';
  2. import { useRef } from 'react';
  3. export function useUniqueId(): string {
  4. // we need to lazy-init this ref.
  5. // otherwise we would call `uniqueId`
  6. // on every render. unfortunately
  7. // useRef does not have lazy-init builtin,
  8. // like useState does. we do it manually.
  9. const idRefLazy = useRef<string | null>(null);
  10. if (idRefLazy.current == null) {
  11. idRefLazy.current = uniqueId();
  12. }
  13. return idRefLazy.current;
  14. }