Skip to content

Instantly share code, notes, and snippets.

@dantman
Created January 23, 2019 06:54
Show Gist options
  • Save dantman/7688b21fc321c2a0516dba51c14188be to your computer and use it in GitHub Desktop.
Save dantman/7688b21fc321c2a0516dba51c14188be to your computer and use it in GitHub Desktop.
A simple hook that returns a unique ID (locally unique and good for dynamic id attributes; not SSR safe)
import warning from 'warning';
import { useState } from 'react';
let idCounter = 0;
function nextId() {
idCounter += 1;
warning(
idCounter < 1e10,
'Id: you might have a memory leak.' +
'The idCounter is not supposed to grow that much.'
);
return idCounter;
}
/**
* A simple hook that returns a unique ID
*/
export default function useId(name) {
const [id] = useState(nextId);
if (process.env.NODE_ENV === 'production') {
return `uid${id}`;
}
return `${name || 'unnamed'}-${id}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment