Extending @forivall's comment
If the whole goal is to link up a <label>
and <input>
elements and they don't depend on props, then instead of using auto generated unique id's, the most optimal and performant approach would be to use useRef
.
useRef returns a mutable ref object whose .current
property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
Meaning, you can use useRef
to mimic instance variables which is not recomputed on props changes. useRef
is not only used to reference a DOM element.
Example using an external random ID generator (e.g. loadash)
import React, { useRef } from 'react'
import uniqueId from 'lodash/utility/uniqueId'
function InputField = (props) => {
const {current: fieldId} = useRef(uniqueId('prefix-'))
return (
<div>
<input id={fieldId} type="checkbox" />
<label htmlFor={fieldId}>label</label>
</div>
);
}
Example using a simple custom random ID generator
import React, { useRef } from 'react'
function InputField = (props) => {
const {current: fieldId} = useRef("prefix-" + (Math.random().toString(36)+'00000000000000000').slice(2, 7))
return (
<div>
<input id={fieldId} type="checkbox" />
<label htmlFor={fieldId}>label</label>
</div>
);
}
Explanation:
The above random ID (Math.random().toString(36)+'00000000000000000').slice(2, 7)
comes from this stackoverflow answer and will always guarantee 5 characters, compared to Math.random().toString(16).slice(-4)
which may return empty strings.
Also, it's important to use a prefix where the prefix must start with a letter ([A-Za-z])
in order for it to be a valid HTML4 id
attribute value.