What's New in React 19: useOptimistic

In this blog post, let's have a look at one of the exciting new feature coming in React 19, React 19 beta is out but some of the features might change in full release.

New Hook : useOptimistic

React 19 introduces a variety of new hooks, one of the interesting ones is for optimistic updates, so what are optimistic updates? An update is optimistic update when the UI is updated before the backend server has actually updated the data, lets understand it with a practical example, imagine you are working on a website which has images and users can like the image, usual pattern would be

      
    declare function apiCall(imageId: string): Promise<number>;

    export interface LikeProps {
    imageId: string;
    likeCount: number;
    onLike: () => void;
    }

    export function LikeImage({ likeCount, imageId, onLike }: LikeProps) {
    const likeImage = () => {
        const newLikeCount = await apiCall(imageId);
        onLike();
    };
    return (
        //UI goes here
        <>
        Total Likes: {likeCount}
        <Button onClick={likeImage}>Like</Button>
        </>
     );
    }
  

As it could be seen that to update the likeCount we need to wait while server processes the request, it could range from few milliseconds to a second, depending upon server load.

Let see how we can use the new hook useOptimistic

      
    declare function apiCall(imageId: string): Promise<number>;
    
    export interface LikeProps {
        imageId: string;
        likeCount: number;
        onLike: () => void;
    }

    export function LikeImage({ likeCount, imageId, onLike }: LikeProps) {
    const [optimisticLikeCount,setOptimisticLikeCount] = useOptimistic(likeCount)
    const likeImage = () => {
        setOptimisticLikeCount(prev => prev+1);
        const newLikeCount = await apiCall(imageId);
        onLike();
    };
    return (
        //UI goes here
        <>
        Total Likes: {optimisticLikeCount}
        <Button onClick={likeImage}>Like</Button>
        </>
     );
    }
  

As from the above implementation you can see how with useOptimistic hook the like count will change instantly and once the server processes the request, the component will re-render to reflect the like count from server, this results in improved user experience as user will get immediate feedback and the application will seem faster.

In upcoming posts we will discuss more of the new features.