use useOptimistic hook in react for WishlistHeart and instead of fetching getwishlist each time, introduce a newprop isInWishlist...
and fetch it once in productlist...
WishlistHeart.jsx:
import React, { useState, useEffect } from 'react';
import { Heart } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import {
AlertDialog,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
Reference
useOptimistic(state, updateFn)
Usage
Optimistically updating forms
Reference
useOptimistic(state, updateFn)
useOptimistic is a React Hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending.
This state is called the “optimistic” state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete.
import { useOptimistic } from 'react';
function AppContainer() {
const [optimisticState, addOptimistic] = useOptimistic(
state,
// updateFn
(currentState, optimisticValue) => {
// merge and return new state
// with optimistic value
}
);
}
See more examples below.
Parameters
state: the value to be returned initially and whenever no action is pending.
updateFn(currentState, optimisticValue): a function that takes the current state and the optimistic value passed to addOptimistic and returns the resulting optimistic state. It must be a pure function. updateFn takes in two parameters. The currentState and the optimisticValue. The return value will be the merged value of the currentState and optimisticValue.
Returns
optimisticState: The resulting optimistic state. It is equal to state unless an action is pending, in which case it is equal to the value returned by updateFn.
addOptimistic: addOptimistic is the dispatching function to call when you have an optimistic update. It takes one argument, optimisticValue, of any type and will call the updateFn with state and optimisticValue.
Usage
Optimistically updating forms
The useOptimistic Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server’s response to reflect the changes, the interface is immediately updated with the expected outcome.
For example, when a user types a message into the form and hits the “Send” button, the useOptimistic Hook allows the message to immediately appear in the list with a “Sending…” label, even before the message is actually sent to a server. This “optimistic” approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the “Sending…” label is removed.
Example:
import { useOptimistic, useState, useRef } from "react";
import { deliverMessage } from "./actions.js";
React 19 new features:
React 19 - Vercel
Michael NovotnyDirector of Developer Experience
17–22 minutes
Explore React 19 and how to start using it on Vercel today.
React 19 is near. The React Core Team announced a React 19 release candidate (RC) this past April. This major version brings several updates and new patterns, aimed at improving performance, ease of use, and developer experience.
Many of these features were introduced as experimental in React 18, but they will be marked as stable in React 19. Here’s a high-level look at what you need to know to be ready.
Server Components
Server Components are one of the biggest changes to React since its initial release 10 years ago. They act as a foundation for React 19’s new features, improving:
Initial page load times. By rendering components on the server, they reduce the amount of JavaScript sent to the client, resulting in faster initial loads. They also let data queries start on the server before the page is sent to the client.
Code portability. Server Components let developers write components that can run on both the server and client, which reduces duplication, improves maintainability, and enables easier sharing of logic across your codebase.
SEO. Server-side rendering of components allows search engines and LLMs to crawl and index content more effectively, improving search engine optimization.
We won’t dive deep into Server Components or rendering strategies in this post. However, to understand the significance of Server Components, let’s take a brief look at how React rendering has evolved.
React started with Client-Side Rendering (CSR), which served minimal HTML to the user.
The linked script includes everything about your application—React, third-party dependencies, and all your application code. As your application grew, so did your bundle size. The JavaScript is downloaded and parsed, and then React loads the DOM elements into the empty div. While this was happening, all the user sees is a blank page.
Even when the initial UI finally shows, the page content is still missing, which is why loading skeletons gained popularity. Data is then fetched and the UI renders a second time, replacing loading skeletons with actual content.
React improved with Server-Side Rendering (SSR), which moves the first render to the server. The HTML served to the user wasn’t empty anymore, and it improves how quickly the user saw the initial UI. However, the data still needs to be fetched to display actual content.
React frameworks stepped in to further improve the user experience with concepts like Static-Site Generation (SSG), which caches and renders dynamic data during the build, and Incremental Static Regeneration (ISR), which recaches and rerenders dynamic data on-demand.
This brings us to React Server Components (RSC). For the first time, native to React, we can fetch data before the UI renders and displays to the user.
HTML served to the user is fully populated with actual content on the first render, and there is no need to fetch additional data or render a second time.
Server Components are a big step forward for speed and performance, enabling a better developer and user experience. Learn more about React Server Components.
Credit to Josh W. Comeau for inspiration on the rendering diagrams.
Try Server Components
This Next.js App Router template lets you experience Server Components with just a few clicks.
Deploy Now
New directives
Directives are not a React 19 feature, but they are related. With the introduction of React Server Components, bundlers need to distinguish where components and functions run. To accomplish this, there are two new directives to be aware of when creating React components:
'use client' marks code that runs only on the client. Since Server Components are the default, you will add 'use client' to Client Components when using hooks for interactivity and state.
'use server' marks server-side functions that can be called from client-side code. You do not need to add 'use server' to Server Components, only Server Actions (more on that below). If you’d like to make sure a certain piece of code can only runs on the server, you can use the server-only npm package.
Learn more about Directives.
Actions
React 19 introduces Actions. These functions replace using event handlers and integrate with React transitions and concurrent features.
Actions can be used on both the client and server. For example, you can have a Client Action which replaces previous usage of onSubmit for a form.
Rather than needing to parse the event, the action is directly passed the FormData.
import { useState } from "react";
export default function TodoApp() {
const [items, setItems] = useState([
{ text: "My first todo" },
]);
async function formAction(formData) {
const newItem = formData.get("item");
// Could make a POST request to the server to save the new item
setItems((items) => [...items, { text: newItem }]);
Going further, Server Actions allow Client Components to call async functions executed on the server. This provides additional advantages, like reading the file system or making direct database calls, removing the need for creating bespoke API endpoints for your UI.
Actions are defined with the 'use server' directive and integrate with client-side components.
To call a Server Action in a Client Component, create a new file and import it:
To complement Actions, React 19 introduces three new hooks to make state, status, and visual feedback easier. These are particularly useful when working with forms, but they can also be used on other elements, like buttons.
useActionState
This hook simplifies managing form states and form submissions. Using Actions, it captures form input data, handles validation, and error states, reducing the need for custom state management logic. The useActionState hook also exposes a pending state that can show a loading indicator while the action is being executed.
This hook manages the status of the last form submission, and it must be called from inside a component that is also inside a form.
import { useFormStatus } from "react-dom";
import action from "./actions";
function Submit() {
const status = useFormStatus();
return Submit;
}
export default function App() {
return (
<form action={action}>
<Submit />
</form>
);
}
While useActionState has a built-in pending status, useFormStatus is useful on its own when:
There is no form state
Creating shared form components
There are multiple forms on the same page—useFormStatus will only return status information for a parent form
Learn more about useFormStatus.
useOptimistic
This hook lets you optimistically update the UI before the Server Action finishes executing, rather than waiting for the response. When the async action completes, the UI updates with the final state from the server.
The following example demonstrates optimistically adding a new message to a thread immediately, while the message is also sent to the Server Action for persistence.
The use function offers first-class support for promises and context during rendering. Unlike other React Hooks, use can be called within loops, conditional statements, and early returns. Error handling and loading will be handled by the nearest Suspense boundary.
The following example shows a loading message while the cart items promise resolves.
import { use } from "react";
function Cart({ cartPromise }) {
// use will suspend until the promise resolves
const cart = use(cartPromise);
return cart.map((item) => {item.title});
}
function Page({ cartPromise }) {
return (
/*{ ... }*/
// When `use` suspends in Cart, this Suspense boundary will be shown
<Suspense fallback={<div>Loading...</div>}>
<Cart cartPromise={cartPromise} />
</Suspense>
);
}
This allows you to group components together so they render only when all the components’ data is available.
Learn more about use.
Preloading resources
React 19 adds several new APIs to improve page load performance and user experience by loading and preloading resources such as scripts, stylesheets, and fonts.
prefetchDNS prefetches the IP address of a DNS domain name you expect to connect to.
preconnect connects to a server you expect to request resources from, even if the exact resources are unknown at the time.
preload fetches a stylesheet, font, image, or external script that you expect to use.
preloadModule fetches an ESM module that you expect to use.
preinit fetches and evaluates an external script or fetches and inserts a stylesheet.
preinitModule fetches and evaluates an ESM module.
For example, this React code would result in the following HTML output. Note that links and scripts are prioritized and ordered by how early they should load, not based on the order they are used in React.
// React code
import { prefetchDNS, preconnect, preload, preinit } from "react-dom";
React frameworks frequently handle resource loading like this for you, so you might not have to call these APIs yourself.
Learn more about Resource Preloading APIs.
Other improvements
ref as a prop
There’s no need for forwardRef anymore. React will provide a codemod to make transitioning easier.
function CustomInput({ placeholder, ref }) {
return ;
}
// ...
;
ref callbacks
In addition to ref as a prop, refs can also return a callback function for cleanup. When a component unmounts, React will call the cleanup function.
<input
ref={(ref) => {
// ref created
// Return a cleanup function to reset
// ref when element is removed from DOM.
return () => {
// ref cleanup
};
}}
/>;
Context as a provider
There’s no need for <Context.Provider> anymore. You can use directly instead. React will provide a codemod to convert existing providers.
const ThemeContext = createContext("");
function App({ children }) {
return {children};
}
useDeferredValue initial value
An initialValue option has been added to useDeferredValue. When provided, useDeferredValue will use the value for the initial render and schedule a re-render in the background, returning the deferredValue.
function Search({ deferredValue }) {
// On initial render the value is ''.
// Then a re-render is scheduled with the deferredValue.
const value = useDeferredValue(deferredValue, "");
return ;
}
Document metadata support
React 19 will natively hoist and render title, link, and meta tags, even from nested components. There’s no need for third-party solutions to manage these tags anymore.
React 19 allows controlling stylesheet loading order with precedence. This makes colocating stylesheets near components easier, and React only loads them if they are used.
There are a few points to keep in mind:
If you render the same component in multiple places within your application, React will deduplicate the stylesheet and only include it once in the document.
When server-side rendering, React will include the stylesheet in the head. This ensures that the browser will not paint until it has loaded.
If the stylesheet is discovered after streaming has started, React will ensure that the stylesheet is inserted into the <head> on the client before revealing the content that depends on that stylesheet through a Suspense boundary.
During client-side rendering, React will wait for newly rendered stylesheets to load before committing the render.
<div>
<p>...</p>
{/* Stylesheet "three" below will be inserted between "one" and "two" */}
<link rel="stylesheet" href="three" precedence="default" />
</div>
);
}
Async scripts support
Render async scripts in any component. This makes colocating scripts near components easier, and React only loads them if they are used.
There are a few points to keep in mind:
If you render the same component in multiple places within your application, React will deduplicate the script and only include it once in the document.
When server-side rendering, async scripts will be included in the head and prioritized behind more critical resources that block paint, such as stylesheets, fonts, and image preloads.
<html>
<body>
<Component>
// ...
</Component> // Won't duplicate script in the DOM
</body>
</html>
);
}
Custom Elements support
Custom Elements allow developers to define their own HTML elements as a part of the Web Components specification. In previous versions of React, using Custom Elements has been difficult because React treats unrecognized props as attributes rather than properties.
React 19 adds full support for Custom Elements and passes all tests on Custom Elements Everywhere.
Better error reporting
Error handling improves by removing duplicate error messages.
Previously, React would throw the error twice. Once for the original error, then a second time after failing to automatically recover, followed by information about the error.Previously, React would throw the error twice. Once for the original error, then a second time after failing to automatically recover, followed by information about the error.
Previously, React would throw the error twice. Once for the original error, then a second time after failing to automatically recover, followed by information about the error.
In React 19, the error is only displayed once.In React 19, the error is only displayed once.
In React 19, the error is only displayed once.
Hydration errors improve by logging a single mismatch error instead of multiple errors. Error messages also include information on how to possibly fix the error.
Example of a hydration error message in React 18.Example of a hydration error message in React 18.
Example of a hydration error message in React 18.
Example of an improved hydration error message in React 19.Example of an improved hydration error message in React 19.
Example of an improved hydration error message in React 19.
Hydration errors when using third-party scripts and browser extensions also improve. Previously, elements inserted by third-party scripts or browser extensions would trigger a mismatch error. In React 19, unexpected tags in the head and body will be skipped over and will not throw an error.
Lastly, React 19 adds two new root options in addition to the existing onRecoverableError, to provide better clarity on why the error is happening.
onCaughtError triggers when React catches an error in an Error Boundary.
onUncaughtError triggers when an error is thrown and not caught by an Error Boundary.
onRecoverableError triggers when an error is thrown and automatically recovered.
To optimize your WishlistHeart component using the useOptimistic hook in React, we'll follow these steps:
Fetch the wishlist once in ProductList.jsx.
Pass the isInWishlist prop to each ProductItem and subsequently to WishlistHeart.
Implement the useOptimistic hook in WishlistHeart.jsx to handle optimistic UI updates.
This approach reduces redundant API calls by fetching the wishlist only once and leverages optimistic updates to enhance user experience by immediately reflecting changes in the UI.
1. Update ProductList.jsx to Fetch Wishlist Once
First, modify your ProductList.jsx to fetch the user's wishlist once when the component mounts. This fetched wishlist will be stored in the state and passed down to each ProductItem as a prop.
The isInWishlist state is now managed by the parent (ProductList.jsx) and passed down as a prop.
Implemented useOptimistic:
Utilized the useOptimistic hook to manage the currentIsInWishlist state.
The useOptimistic hook takes the initial isInWishlist prop and provides an optimistic state that can be updated before the actual async operation completes.
Optimistic UI Update:
When the user clicks the heart icon, addOptimistic(!currentIsInWishlist) is called to immediately reflect the change in the UI.
This provides instant feedback to the user, enhancing the perceived performance.
API Call Handling:
After the optimistic update, an API call is made to add or remove the product from the wishlist.
On success, the parent’s wishlist state is updated using addToWishlist or removeFromWishlist.
On failure, the optimistic update is reverted by calling addOptimistic(currentIsInWishlist).
Dialog Handling for Unauthenticated Users:
Maintained the existing dialog logic to prompt users to sign in if they're not authenticated.
4. Additional Considerations
Ensure Token Availability:
Make sure that the token is available in localStorage and is set correctly upon user authentication.
Handle Edge Cases:
Consider handling cases where the wishlist might not be fetched correctly, or when multiple wishlist operations happen simultaneously.
Error Handling:
Enhance error handling by providing user feedback when adding or removing items from the wishlist fails.
Performance Optimization:
If the wishlist grows large, consider using a Set for more efficient lookup operations instead of an array.
5. Final Thoughts
By fetching the wishlist once in the ProductList.jsx and passing the isInWishlist prop down to each WishlistHeart component, you significantly reduce the number of API calls, enhancing the performance of your application. The useOptimistic hook further improves user experience by ensuring that the UI responds immediately to user actions, even before the server confirms the changes.
Ensure that all components are correctly updated and that the useOptimistic hook is properly supported in your React version. Test the implementation thoroughly to confirm that the optimistic updates behave as expected and that the UI remains in sync with the server state.