useOptimistic
useOptimistic is a hook in React that optimistically updates the UI while an async operation is still underway. It allows you to immediately show the expected result while the form submission is in progress. If the submission is successful, the UI remains the same; if it fails, the UI reverts back to the previous state.
Importing the Hook​
Import the useOptimistic hook from the React library:
import { useOptimistic, useState } from "react";
Using useOptimistic​
The useOptimistic hook can be used inside your functional component to manage optimistic state updates. Here's a breakdown of how to use it:
Basic Usage​
const [optimisticState, setOptimisticState] = useOptimistic(actualState, updateFn);
Hook Parameters​
actualState: The value of the optimistic state when no action is pending.updateFn(optional): A function that takes the actual state and the value passed to thesetOptimisticStatemethod and calculates theoptimisticState. If this parameter is not specified, the optimistic state is equal to the new value.
Hook Return Values​
optimisticState: The optimistic (temporary) value shown while the action is pending.setOptimisticState: A function that sets the optimistic state to a new value.
Example​
Here is an example of how to use the useOptimistic hook in a form component that performs an async operation to change the title of the page:
import { useOptimistic, useState } from "react";
const OptimisticComponent = () => {
const [title, setTitle] = useState("Title");
const [optimisticTitle, setOptimisticTitle] = useOptimistic(title);
const [error, setError] = useState(null);
const pending = title !== optimisticTitle;
const handleSubmit = async (formData) => {
setError(null);
setOptimisticTitle(formData.get("title"));
try {
const updatedTitle = await submitTitle(formData);
setTitle(updatedTitle);
} catch (e) {
setError(e);
}
};
return (
<div>
<h2>{optimisticTitle}</h2>
<p>{pending && "Updating..."}</p>
<form action={handleSubmit}>
<input type="text" name="title" placeholder="Change Title" />
<button type="submit" disabled={pending}>
Submit
</button>
</form>
<div className="error">{error && error}</div>
</div>
);
};
Explanation​
- The component displays the optimistic value of the title, which is set to
titlestate when no action is pending. - A
pendingvariable is defined to check if the current and optimistic state do not match. Based on this, a pending text is displayed and the submit button is disabled. - Any error encountered during the async operation is displayed.
Async Operation​
Here's how to call the async function that either resolves or rejects the request:
import { submitTitle } from "../../actions";
const OptimisticComponent = () => {
const [title, setTitle] = useState("Title");
const [optimisticTitle, setOptimisticTitle] = useOptimistic(title);
const [error, setError] = useState(null);
const pending = title !== optimisticTitle;
const handleSubmit = async (formData) => {
setError(null);
setOptimisticTitle(formData.get("title"));
try {
const updatedTitle = await submitTitle(formData);
setTitle(updatedTitle);
} catch (e) {
setError(e);
}
};
return (
<div>
<h2>{optimisticTitle}</h2>
<p>{pending && "Updating..."}</p>
<form action={handleSubmit}>
<input type="text" name="title" placeholder="Change Title" />
<button type="submit" disabled={pending}>
Submit
</button>
</form>
<div className="error">{error && error}</div>
</div>
);
};
Benefits​
Using the useOptimistic hook improves the user experience by immediately reflecting changes in the UI, even while the underlying async operations are still pending. It helps in managing a smoother and more responsive interface.

Conclusion​
The useOptimistic hook in React allows you to optimistically update the UI during async operations, providing a better user experience by showing the expected result immediately. It simplifies the process of managing optimistic state updates and ensures a more responsive interface for your users.