All files / libs/ext/react/hooks/src/lib/use-unique-id useUniqueId.ts

100% Statements 24/24
100% Branches 3/3
100% Functions 1/1
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 251x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x  
import { uniqueId } from 'lodash-es';
import { useState } from 'react';
 
/**
 * Generate a unique id if no id is given as parameter.
 * The random id is generated on mount. If prefix changes, the id is not updated.
 *
 * @param id - If provided, will be returned without generating a new value.
 * @param prefix - If no id provided, will generate a unique id with this prefix.
 */
export const useUniqueId = ({
  id,
  prefix,
}: {
  id?: string;
  prefix?: string;
} = {}): string => {
  // Generate a random id on mount. Never update.
  // eslint-disable-next-line react/hook-use-state
  const [randomId] = useState(() => uniqueId(prefix));
 
  // Return the id if provided, fallback on generated id.
  return id ?? randomId;
};