Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active June 16, 2023 15:26
Show Gist options
  • Select an option

  • Save sorenlouv/fc897c1629979e669714893df966b1b7 to your computer and use it in GitHub Desktop.

Select an option

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;
}
@mbelsky

mbelsky commented Mar 24, 2020

Copy link
Copy Markdown

@akomm I've tested my solution with this demo: https://codesandbox.io/s/determined-goldstine-qj761 A component rerenders there on click event and uniqueId stays same.

How should I change this demo to see behavior that you described?

@akomm

akomm commented Mar 25, 2020

Copy link
Copy Markdown

@mbelsky in your example, its the componentId which is the same, not uniqueId.

@mbelsky

mbelsky commented Mar 25, 2020

Copy link
Copy Markdown

@akomm could you explain please what the difference between them and how I can reproduce the issue that you described above?

but your example will increment the ID on each render call, even thought no new ID is required

I'm still not understanding what wrong with this solution

@akomm

akomm commented Mar 25, 2020

Copy link
Copy Markdown

just log the uniqueId to console in useComponentId and see if it is the same? You tell uniqueId is the same and post an example where you render the componentId. :)

@mbelsky

mbelsky commented Mar 25, 2020

Copy link
Copy Markdown

@akomm got it, thanks. I've updated originally post & demo. btw there is another interesting issue: uniqueId-s are odd numbers now. I'll try to find a solution for that

@akomm

akomm commented Mar 25, 2020

Copy link
Copy Markdown

@mbelsky

Your proposal worked. Its just a question if you want to increment the id forever on each render or not. The solution would be, as I proposed above, to replace uniqueId++ with () => uniqueId++.

@akomm

akomm commented Mar 25, 2020

Copy link
Copy Markdown

@mbelsky

codesandbox is flaky there, hence your odd numbers. Try it locally, it should work. I used to use codepen, then codesandbox came out and was better. Liked it. But recently it got more and more flaky. A pure bugfeast. Might be there bundler configuration or life reload that messes it up. IF you do some tests, you notice on life reload its rendered twice.

@mbelsky

mbelsky commented Mar 25, 2020

Copy link
Copy Markdown

codesandbox is flaky there, hence your odd numbers. Try it locally, it should work

I'll try, thank you!

@VWSCoronaDashboard8

Copy link
Copy Markdown

For anyone landing here using Typescript, it is generally advised to avoid the use of null. It simplifies types, and once you try to stop using it you realize you really don't need it 95% of the time because the JS already gives you undefined to work with.

So here's a slight adaptation:

let uniqueId = 0;
const getUniqueId = () => uniqueId++;

export function useComponentId() {
  const idRef = useRef<number>();
  if (idRef.current === undefined) {
    idRef.current = getUniqueId();
  }
  return idRef.current;
}

@kmurph73

kmurph73 commented Jan 13, 2021

Copy link
Copy Markdown

Using this with Strict Mode will give you a different value on the 2nd render. I assume this is okay to use otherwise, and it's just some quirk of Strict Mode that produces differing values? I've used it in production w/o apparent issue...

Edit: looks like it's the result of having a harmless side effect: react/react#20826

Trying to move away from this Hook in order to be StrictMode compatible (despite it working 100% fine otherwise)... wish there was a React.useComponentName Hook...

@notthatnathan

notthatnathan commented Feb 24, 2021

Copy link
Copy Markdown

The useRef version works in my testing, but why not just set the initial value rather than checking undefined/null and assigning? Am I missing something here?

export function useComponentId() {
  const id = useRef(getUniqueId());
  return id.current;
}

(edited, forgot .current in the return)

@akomm

akomm commented Feb 27, 2021

Copy link
Copy Markdown

@notthatnathan it has actually been explained here.

@notthatnathan

Copy link
Copy Markdown

Oops, missed it. Thanks.

@notthatnathan

Copy link
Copy Markdown

FWIW, after generating the id (I used shortid()) as the initial value (as mentioned above), it doesn't change in my testing. I don't believe the undefined check and reassignment is necessary with refs.

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

const id = useRef(process.env.NODE_ENV === 'test' ? `test-${title}` : shortid());

@akomm

akomm commented Mar 2, 2021

Copy link
Copy Markdown

FWIW, after generating the id (I used shortid()) as the initial value (as mentioned above), it doesn't change in my testing. I don't believe the undefined check and reassignment is necessary with refs.

Why is it not needed and how do the two things relate (I don't know your shortid implementation).

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

const id = useRef(process.env.NODE_ENV === 'test' ? `test-${title}` : shortid());

You add test-related code in a component? And also you change behavior depending on how id is used the outcome might be different in test than prod.

@notthatnathan

notthatnathan commented Mar 2, 2021

Copy link
Copy Markdown

You add test-related code in a component? And also you change behavior depending on how id is used the outcome might be different in test than prod.

Doesn't change behavior, just changes the id. Otherwise every run of your test, you get snapshot updates (new id on mount), which defeats the purpose of snapshots.

Why is it not needed and how do the two things relate (I don't know your shortid implementation).

I'm not sure I understand the question. I'm just saying that this:

  const idRef = useRef(null);
  if (idRef.current === null) {
    idRef.current = getUniqueId()
  }
  return idRef.current;

and this

  const idRef = useRef(getUniqueId());
  return idRef.current;

both return a unique ID that doesn't change on re-render. Which makes sense, refs wouldn't be useful if the initial value changed. Log from the calling component to see what I mean.

(shortid is just an id-generating package my org uses)

updated, typo in the second code example

@akomm

akomm commented Mar 4, 2021

Copy link
Copy Markdown

You add test-related code in a component? And also you change behavior depending on how id is used the outcome might be different in test than prod.

Doesn't change behavior, just changes the id. Otherwise every run of your test, you get snapshot updates (new id on mount), which defeats the purpose of snapshots.

It does. You use different ID generation methods. If one of the different methods generate non-unique ID, it will work in one, but fail in the other or lead to different results, depending on how you use the generated ID.

Sorry. I don't get what you are talking about. You've just changed things replying to my initial question. Why is it null instead of undefined? Also you did not answer why the undefined check is not needed. I don't understand the problem.

@bluenote10

bluenote10 commented Mar 6, 2021

Copy link
Copy Markdown

In cases where I don't need globally unique IDs, but rather IDs unique per component I'm using this hook:

export function useIdGenerator(): () => number {
  const ref = useRef(0);

  function getId() {
    ref.current += 1;
    return ref.current;
  }

  return getId;
}

@meglio

meglio commented Jul 9, 2021

Copy link
Copy Markdown

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

@Izhaki

Izhaki commented Mar 16, 2022

Copy link
Copy Markdown

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

Here is a more robust implementation that also supports SSR.

@airtonix

airtonix commented Apr 1, 2022

Copy link
Copy Markdown

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

mbonaci commented Jun 16, 2023

Copy link
Copy Markdown

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