Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active June 16, 2023 15:26
Show Gist options
  • Save sorenlouv/fc897c1629979e669714893df966b1b7 to your computer and use it in GitHub Desktop.
Save sorenlouv/fc897c1629979e669714893df966b1b7 to your computer and use it in GitHub Desktop.
React hook for getting a unique identifier for a component
import { useRef } from 'react';
let uniqueId = 0;
const getUniqueId = () => uniqueId++;
export function useComponentId() {
const idRef = useRef(getUniqueId());
return idRef.current;
}
@meglio
Copy link

meglio commented Jul 9, 2021

On a side note, nanoId is considerably faster than shortId or uniqueId according to their benchmarks.

@Izhaki
Copy link

Izhaki commented Mar 16, 2022

There is an open issue for this on the react repo.

Here is a more robust implementation that also supports SSR.

@airtonix
Copy link

airtonix commented Apr 1, 2022

Also, for test snapshot support, you'll want a predictable id, maybe using a different prop from the instance.

You shouldn't be using snapshots at all. write proper tests.

@mbonaci
Copy link

mbonaci commented Jun 16, 2023

For anyone stumbling upon this in 2023 there's React.useId for this very purpose since React v18.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment