
The React useId()
hook is used to generate a unique identifier (ID) for a component instance. The ID is then used to assign IDs to elements that are tied to the component instance.
In some cases, the useId
hook is useful when you need a unique identifier for elements that don’t have a fixed ID, such as when iterating over a set of data in a list or table.
In this guide, we’ll look at how to use the React useId
hook with examples.
Usage Example
First import the useId
hook from the react package:
import { useId } from 'react';
// Create a constant to store our ID:
export function MyComponent() {
const myId = useId();
// Pass our ID to the element in question:
return <div id={myId}>hello</div>;
}
And that’s it! Your element now has a unique ID that is tied to the component instance.
You can also use the useId
hook in other contexts example, if you have a group of checkboxes, you can create an ID for each checkbox and store it in an array.
import { useId } from 'react';
// Create a constant to store our ID:
export function MyComponent() {
const ids = [];
// or a one-liner
// const ids = Array.from({length: 5}).map(_ => useId());
for (let i = 0; i < 5; i++) {
const id = useId();
ids.push(id);
}
// Now when we render each checkbox, we can use the ID from the array
return (
<form>
<input type='checkbox' id={ids[0]} />
<input type='checkbox' id={ids[1]} />
</form>
);
}
Real-world usecase for useId
Following are two real-world examples of how you would go about using this hook in your react application.
Creating a reusable login form component
When a user logs in they can use the useId
hook to track the user’s session and store the associated data in localstorage
.
import React, {
useState,
useEffect,
useReducer,
useCallback,
useId,
} from 'react';
const LoginForm = () => {
const [username, setUsername] = useState(''); // Used to track input field
const [password, setPassword] = useState(''); // Used to track input field
const [error, setError] = useState(null); // Used to track errors
const [isLoggingIn, setIsLoggingIn] = useState(false); // Used to track login state
const loginId = useId(); // Used to track login session
const allowLogin = (username, password) => {
// auth logic here...
};
useEffect(() => {
if (isLoggingIn) {
localStorage.setItem('loginId', loginId);
}
}, [isLoggingIn, loginId]);
const onSubmit = useCallback(
(e) => {
e.preventDefault();
setIsLoggingIn(true);
setError(null);
if (allowLogin(username, password)) {
// login success
// set user session here
} else {
setError('Username or password is incorrect');
}
},
[username, password]
);
return (
<form onSubmit={onSubmit}>
<fieldset>
<input
type='text'
name='username'
id='username'
onChange={(e) => setUsername(e.target.value)}
min='8'
/>
<input
type='password'
name='password'
id='password'
onChange={(e) => setPassword(e.target.value)}
min='8'
/>
</fieldset>
{error && <p>{error}</p>}
<button type='submit' disabled={isLoggingIn} />
<Loginbutton />
</form>
);
};
Accessing user preferences
useId
can be used to store user preferences such as font size, colors, etc. and use that data to customize the user’s experience.
import React, {
useState,
useEffect,
useReducer,
useCallback,
useId,
} from 'react';
//Set the default settings
const defaultSettings = {
fontSize: '12px',
color: '#000000',
showImages: true,
};
// Retrieve user preferences from storage
const userId = 'dbc1a7f5-5209-4296-8092-2bcaa0ee48be'; // random string
const storedSettings = localStorage.getItem(userId);
const settings = storedSettings ? JSON.parse(storedSettings) : defaultSettings;
const LoginForm = () => {
//Apply user preferences to the page
document.body.style.fontSize = settings.font.size;
document.body.style.color = settings.color;
document.body.style.backgroundImage = settings.showImages
? 'url(img.jpg)'
: 'none';
//Save user preferences into storage
const [, setSettings] = useState(settings);
const userId = useId();
useEffect(() => {
localStorage.setItem(userId, JSON.stringify(settings));
}, [userId, settings]);
//Handle input changes
const handleChange = useCallback((e) => {
e.preventDefault();
const { name, value } = e.target;
setSettings((prevState) => {
return { ...prevState, [name]: value };
});
}, []);
return (
<form>
<label>Font Size</label>
<input
type='text'
name='fontSize'
value={settings.fontSize}
onChange={handleChange}
/>{' '}
<label>Color</label>
<input
type='text'
name='color'
value={settings.color}
onChange={handleChange}
/>{' '}
<label>Show Images?</label>
<input
type='checkbox'
name='showImages'
checked={settings.showImages}
onChange={handleChange}
/>
</form>
);
};
export default LoginForm;
And that’s how you can use the React useId
hook with examples. We hope you’ve found this guide useful!
Leave a Reply