Created
January 23, 2019 06:54
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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