React Hooks 3: New Hooks in React 18

Carolina Cobo
3 min readAug 23, 2022
image source: Mydeen S N

I’m still familiarising myself with the new updates in React 18 such as Concurrency, Automatic Batching, and the new Transitions and Suspense features (I might write about it). Still, to finish this section I’m going to go over the new Hooks in React 18.

1. useId

This new Hook will generate a unique ID on both sides, client and server while avoiding hydration mismatches.

This Hook will be useful mostly in component libraries that are integrated with Accessibility APIs that require unique IDs.

Remember: useId is not for generating keys in a list, the keys should be generated from your data.

For a basic example, pass the id directly to the elements that need it:

function Checkbox() {
const id = useId();
return (
<>
<label htmlFor={id}>This is an Example</label>
<input id={id} type="checkbox" name="react"/>
</>
);
};

For multiple IDs in the same component, append a suffix using the same id:

function NameFields() {
const id = useId();
return (
<div>
<label htmlFor={id + '-firstName'}>First Name</label>
<div>
<input id={id + '-firstName'} type="text" />
</div>
<label htmlFor={id + '-lastName'}>Last Name</label>
<div>
<input id={id + '-lastName'} type="text" />
</div>
</div>
);
}

2. useTransition and startTransition

They will allow you to mark some state updates as not urgent, some updates might be considered urgent by default (updating a text input) and these ones will be allowed to interrupt the non-urgent ones.

const [isPending, startTransition] = useTransition();//startTransition lets you mark updates in the provided callback as transitions:startTransition(() => {
setCount(count + 1);
})
//isPending indicates when a transition is active to show a pending state:function App() {
const [isPending, startTransition] = useTransition();
const [count, setCount] = useState(0);

function handleClick() {
startTransition(() => {
setCount(c => c + 1);
})
}

return (

--

--

Carolina Cobo

Frontend Software Engineer @ Genesys | Career switcher