The useId() hook in React

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!

React 18 added a new hook named useId(). Its only scope is to generate unique IDs.

For example, the below React code:

import { useId } from "react";

function App() {
  const myId = useId()
  // myId will have a value like ':r0:'

  return(<div>
    <input type="checkbox" id={myId} name="newsletter" />
    <label for={myId}>Subscribe to newsletter</label>
  </div>)
}

Will output this HTML:

<div>
    <input type="checkbox" id=":r0:" name="newsletter">
    <label for=":r0:">Subscribe to newsletter</label>
</div>

I find it a nice tool to reduce the mental load of figuring out unique values for id values.

Specifying a prefixes for useId()

You can also specify a prefix to be appended to the result of useId() by using the ReactDOM.createRoot(), and also gain some performance improvements for your React components.

import { useId } from "react";
import { createRoot } from 'react-dom/client'

function App() {
  const myId = useId()

  return(<div>
    <input type="checkbox" id={myId} name="newsletter" />
    <label for={myId}>Subscribe to newsletter</label>
  </div>)
}

const root = createRoot(document.getElementById('root'), {
  identifierPrefix: 'my-prefix-for-ids-'
});
root.render(<App />);

In this case, the output for useId() will be :my-prefix-for-ids-r0:.

You can checkout here the codepen for this example.

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X