Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Created May 26, 2021 23:22
Show Gist options
  • Save VitorLuizC/c56b909953b9f001c82367d5f44d2013 to your computer and use it in GitHub Desktop.
Save VitorLuizC/c56b909953b9f001c82367d5f44d2013 to your computer and use it in GitHub Desktop.
React.js useIdentify hook that generates an unique id with really random generated numbers for each name provided.
import { useCallback, useMemo } from 'react';
import generateHash from './generateHash.js';
export type Identify = (name: string) => string;
function useIdentify(): Identify {
const ids = useMemo(() => new Map<string, string>(), []);
return useCallback((name) => {
if (!ids.has(name)) {
ids.set(name, `id-${generateHash()}`);
}
// `!` was used because it was checked in the `if` above.
return ids.get(name)!;
}, [ids]);
}
export default useIdentify;
import fromByteToHex from './fromByteToHex';
function generateHash(size = 8): string {
const values = new Uint8Array(size / 2);
// Fill in values array with really random numbers.
window.crypto.getRandomValues(values);
return Array.from(values, fromByteToHex).join('');
}
export default generateHash;
function fromByteToHex(byte: number): string {
return byte.toString(16).padStart(2, '0');
}
export default fromByteToHex;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment