DEV Community

Exploring the New useOptimistic Hook in React: Enhancing UI with Optimistic Updates

Barry Michael Doyle on October 19, 2023

If you're as excited about React's new features as I am, you've probably been keeping an eye on the experimental builds. In this post, we're going ...
Collapse
 
dumebii profile image
Dumebi Okolo

Wow. Thanks for sharing!

Collapse
 
barrymichaeldoyle profile image
Barry Michael Doyle

Iā€™m glad you found this interesting! Hopefully this prepares you for when it is properly ready! šŸ„³

Collapse
 
dumebii profile image
Dumebi Okolo

Yesss. Thank you.

Collapse
 
ariannargesi profile image
Arian Nargesi

Thank you @barrymichaeldoyle for this great explanation.
How do we handle errors? What to do when network request fails? Is there any mechanism to undo the optimistic update?

Collapse
 
barrymichaeldoyle profile image
Barry Michael Doyle

Sorry I've taken so long to get back to you.

The way the useOptimistic hook works is that the optimistic update resets when the the asynchronous form action is completed and the actual rendered value gets replaced by the new todos. It's not really shown in my example code in this post.

So in the case of an error - which will be handled in createTodo - the optimistic value will be cleared when the promise rejects because todos doesn't change. The way you decide to handle an error specifically is up to you e.g. you could render a toast, or show an error message under the todos list, up to you.

Collapse
 
mandiaroux profile image
Mandia Roux

Looks awesome, thanks for the clear and consise explanation šŸ˜€

Collapse
 
barrymichaeldoyle profile image
Barry Michael Doyle

It's such a pleasure and thank you for the encouraging feedback!

Collapse
 
jc005789 profile image
jayden

Why useOptimistic is undefined in my app after I installed like so

npm install react@experimental react-dom@experimental

I tried import { useOptimistic } from 'react' as well but does not work.

It keeps erroring out saying 0__.useOptimistic) is not a function or its return value is not iterable

Collapse
 
ahmetkca profile image
ahmetkca

What if you mutate your data somewhere else? How would you use useOptimistic hook then? Perhaps, with state management libraries such as zustand?

Collapse
 
ashukumar2001 profile image
Ashu Kumar

You can wrap your action into a transition
`const [isPending, startTransition] = useTransition();

const onUpdate = () => {
startTransition(()=> {
optimisticUpdate();
})
}

`

Collapse
 
barrymichaeldoyle profile image
Barry Michael Doyle

In that scenario I'd recommend going with something like zustand yes.

Collapse
 
syedmuhammadaliraza profile image
Syed Muhammad Ali Raza

Thanks for sharing!