

Have you ever ever clicked a button and waited for one thing to occur whereas the web page simply sat there doing nothing? That delay could make an app really feel sluggish. Wouldn’t it’s nice if the UI responded immediately, even earlier than the precise knowledge was up to date?
That is the place React’s useOptimistic
hook is available in! Launched in React 18.2, it means that you can present prompt suggestions to customers by exhibiting an anticipated outcome instantly—making your app really feel quick and responsive. As a substitute of ready for a community request to finish, useOptimistic
quickly updates the UI with a predicted state—a way referred to as optimistic UI.
On this weblog, we’ll discover how useOptimistic
works, why it’s helpful, and how one can implement it to enhance the person expertise in your React purposes. Let’s dive in!


Understanding useOptimistic
Syntax:
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
- state – The preliminary state earlier than any optimistic updates.
- updateFn – A operate that takes the present state and an optimistic worth, merges them, and returns the brand new state.
- optimisticState – The state that updates optimistically earlier than the async motion is confirmed.
- addOptimistic – A operate you name to use an optimistic replace.
Why Use useOptimistic?
When constructing interactive purposes, customers count on prompt suggestions once they take an motion. Nonetheless, community latency could cause delays between person actions and knowledge updates, resulting in a irritating expertise.
Through the use of useOptimistic, you’ll be able to:
- Present fast UI suggestions with out ready for a response from the server.
- Enhance perceived efficiency and responsiveness.
- Scale back the necessity for complicated loading states within the UI.
An awesome instance of it is a bookmarking function in a weblog software. Let’s see how we will implement it.
Instance: Bookmarking Posts
1. Preliminary Setup
First, we outline an array of weblog posts and use useState to handle their state:
const [posts, setPosts] = useState([
{ id: 1, title: "React Optimistic UI", bookmarked: false },
{ id: 2, title: "Understanding React Hooks", bookmarked: false },
]);
2. Implementing useOptimistic
We initialize useOptimistic with the present state and outline an replace operate to optimistically toggle the bookmark standing:
const [optimisticPosts, addOptimisticPost] = useOptimistic(
posts,
(state, postId) => {
return state.map((submit) =>
submit.id === postId ? { ...submit, bookmarked: !submit.bookmarked } : submit
);
}
);
This operate will toggle the bookmarked standing within the UI earlier than making the precise API request.
3. Dealing with Bookmark Clicks
When a person clicks the bookmark button, we optimistically replace the UI earlier than performing the precise replace on the server:
const handleBookmark = async (postId) => {
startTransition(async () => {
addOptimisticPost(postId);
attempt {
const response = await fetch("/posts/bookmark", {
technique: "POST",
headers: { "Content material-Sort": "software/json" },
physique: JSON.stringify({ postId }),
});
if (!response.okay) throw new Error("Didn't replace bookmark");
setPosts((currentPosts) =>
currentPosts.map((submit) =>
submit.id === postId ? { ...submit, bookmarked: !submit.bookmarked } : submit
)
);
console.log("Bookmark up to date on server");
} catch (error) {
console.error("Didn't replace bookmark:", error);
// Revert UI state on failure
addOptimisticPost(postId);
}
});
};
Right here’s what occurs step-by-step:
- The add OptimisticPost(postId) operate known as to replace the UI immediately.
- A community request is shipped to replace the bookmark standing within the backend.
- If the request is profitable, the precise state is up to date utilizing setPosts().
- If the request fails, the UI state is reverted to replicate the precise server state.
4. Rendering the Posts
We use optimisticPosts to render the UI, making certain prompt suggestions when customers work together with the bookmark button:
{optimisticPosts.map((submit) => (
{submit.title}
))}
When to Use useOptimistic
Think about using useOptimistic when:
- The person’s motion is very prone to succeed (e.g., liking a submit, including an merchandise to favorites).
- You wish to present prompt UI updates with out ready for a backend response.
- The results of a brief incorrect state are minimal (e.g., a failed bookmark replace may be retried later).
Limitations of useOptimistic
Whereas useOptimistic is helpful, it’s necessary to pay attention to its limitations:
- If the server replace fails, you’ll have to deal with error states appropriately (e.g., reverting the UI, exhibiting a retry button).
- It’s not appropriate for circumstances the place strict knowledge accuracy is required (e.g., processing funds).
By leveraging useOptimistic, you’ll be able to considerably enhance the responsiveness of your React purposes. Strive integrating it into your initiatives and see the distinction it makes! 🚀
Conclusion
useOptimistic is a robust instrument for creating smoother UI interactions. In our instance, it ensures that bookmarking posts feels instantaneous whereas nonetheless syncing adjustments with the backend. By offering fast visible suggestions, it tremendously enhances the person expertise and makes purposes really feel extra responsive.
With out useOptimistic, customers would possibly expertise a noticeable delay between clicking the bookmark button and seeing the UI replace. By implementing optimistic updates, we make our app really feel quicker and extra interactive.