62:29 Warning: React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead. react-hooks/exhaustive-deps
Also there is an ui issue, when I lose focus I don't want the animation of search results falls down, it should disappear immediately without any animations...
improve performance and stability as well...
Make the page more compitable...
Also I'm using react 19 and nextjs 15...
'use client';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, X } from 'lucide-react';
import Image from 'next/image';
import debounce from 'lodash/debounce';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
const ITEMS_PER_PAGE = 5; // Define items per page for consistency
What's new in react 19:
What’s new in React 19
Actions
A common use case in React apps is to perform a data mutation and then update state in response. For example, when a user submits a form to change their name, you will make an API request, and then handle the response. In the past, you would need to handle pending states, errors, optimistic updates, and sequential requests manually.
For example, you could handle the pending and error state in useState:
In React 19, we’re adding support for using async functions in transitions to handle pending states, errors, forms, and optimistic updates automatically.
For example, you can use useTransition to handle the pending state for you:
// Using pending state from Actions
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
The async transition will immediately set the isPending state to true, make the async request(s), and switch isPending to false after any transitions. This allows you to keep the current UI responsive and interactive while the data is changing.
Note
By convention, functions that use async transitions are called “Actions”.
Actions automatically manage submitting data for you:
code
Pending state: Actions provide a pending state that starts at the beginning of a request and automatically resets when the final state update is committed.
Optimistic updates: Actions support the new useOptimistic hook so you can show users instant feedback while the requests are submitting.
Error handling: Actions provide error handling so you can display Error Boundaries when a request fails, and revert optimistic updates to their original value automatically.
Forms: <form> elements now support passing functions to the action and formAction props. Passing functions to the action props use Actions by default and reset the form automatically after submission.
Building on top of Actions, React 19 introduces useOptimistic to manage optimistic updates, and a new hook React.useActionState to handle common cases for Actions. In react-dom we’re adding Actions to manage forms automatically and useFormStatus to support the common cases for Actions in forms.
In React 19, the above example can be simplified to:
// Using Actions and useActionState
function ChangeName({ name, setName }) {
const [error, submitAction, isPending] = useActionState(
async (previousState, formData) => {
const error = await updateName(formData.get("name"));
if (error) {
return error;
}
redirect("/path");
return null;
},
null,
);
return (
Update
{error && {error}}
);
}
In the next section, we’ll break down each of the new Action features in React 19.
New hook: useActionState
To make the common cases easier for Actions, we’ve added a new hook called useActionState:
const [error, submitAction, isPending] = useActionState(
async (previousState, newName) => {
const error = await updateName(newName);
if (error) {
// You can return any result of the action.
// Here, we return only the error.
return error;
}
code
// handle success
return null;
},
null,
);
useActionState accepts a function (the “Action”), and returns a wrapped Action to call. This works because Actions compose. When the wrapped Action is called, useActionState will return the last result of the Action as data, and the pending state of the Action as pending.
Note
React.useActionState was previously called ReactDOM.useFormState in the Canary releases, but we’ve renamed it and deprecated useFormState.
See #28491 for more info.
For more information, see the docs for useActionState.
React DOM: Actions
Actions are also integrated with React 19’s new features for react-dom. We’ve added support for passing functions as the action and formAction props of , , and elements to automatically submit forms with Actions:
When a Action succeeds, React will automatically reset the form for uncontrolled components. If you need to reset the manually, you can call the new requestFormReset React DOM API.
For more information, see the react-dom docs for , , and .
React DOM: New hook: useFormStatus
In design systems, it’s common to write design components that need access to information about the they’re in, without drilling props down to the component. This can be done via Context, but to make the common case easier, we’ve added a new hook useFormStatus:
import {useFormStatus} from 'react-dom';
function DesignButton() {
const {pending} = useFormStatus();
return
}
useFormStatus reads the status of the parent as if the form was a Context provider.
For more information, see the react-dom docs for useFormStatus.
New hook: useOptimistic
Another common UI pattern when performing a data mutation is to show the final state optimistically while the async request is underway. In React 19, we’re adding a new hook called useOptimistic to make this easier:
function ChangeName({currentName, onUpdateName}) {
const [optimisticName, setOptimisticName] = useOptimistic(currentName);
return (
Your name is: {optimisticName}
Change Name:
<input
type="text"
name="name"
disabled={currentName !== optimisticName}
/>
);
}
The useOptimistic hook will immediately render the optimisticName while the updateName request is in progress. When the update finishes or errors, React will automatically switch back to the currentName value.
For more information, see the docs for useOptimistic.
New API: use
In React 19 we’re introducing a new API to read resources in render: use.
For example, you can read a promise with use, and React will Suspend until the promise resolves:
import {use} from 'react';
function Comments({commentsPromise}) {
// use will suspend until the promise resolves.
const comments = use(commentsPromise);
return comments.map(comment => {comment});
}
function Page({commentsPromise}) {
// When use suspends in Comments,
// this Suspense boundary will be shown.
return (
<Suspense fallback={Loading...}>
)
}
Note
use does not support promises created in render.
If you try to pass a promise created in render to use, React will warn:
Console
A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework.
To fix, you need to pass a promise from a suspense powered library or framework that supports caching for promises. In the future we plan to ship features to make it easier to cache promises in render.
You can also read context with use, allowing you to read Context conditionally such as after early returns:
import {use} from 'react';
import ThemeContext from './ThemeContext'
function Heading({children}) {
if (children == null) {
return null;
}
// This would not work with useContext
// because of the early return.
const theme = use(ThemeContext);
return (
<h1 style={{color: theme.color}}>
{children}
);
}
The use API can only be called in render, similar to hooks. Unlike hooks, use can be called conditionally. In the future we plan to support more ways to consume resources in render with use.
For more information, see the docs for use.
React Server Components
Server Components
Server Components are a new option that allows rendering components ahead of time, before bundling, in an environment separate from your client application or SSR server. This separate environment is the “server” in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server.
React 19 includes all of the React Server Components features included from the Canary channel. This means libraries that ship with Server Components can now target React 19 as a peer dependency with a react-server export condition for use in frameworks that support the Full-stack React Architecture.
Note
How do I build support for Server Components?
While React Server Components in React 19 are stable and will not break between major versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x.
To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future.
For more, see the docs for React Server Components.
Server Actions
Server Actions allow Client Components to call async functions executed on the server.
When a Server Action is defined with the "use server" directive, your framework will automatically create a reference to the server function, and pass that reference to the Client Component. When that function is called on the client, React will send a request to the server to execute the function, and return the result.
Note
There is no directive for Server Components.
A common misunderstanding is that Server Components are denoted by "use server", but there is no directive for Server Components. The "use server" directive is used for Server Actions.
For more info, see the docs for Directives.
Server Actions can be created in Server Components and passed as props to Client Components, or they can be imported and used in Client Components.
For more, see the docs for React Server Actions.
Improvements in React 19
ref as a prop
Starting in React 19, you can now access ref as a prop for function components:
function MyInput({placeholder, ref}) {
return
}
//...
New function components will no longer need forwardRef, and we will be publishing a codemod to automatically update your components to use the new ref prop. In future versions we will deprecate and remove forwardRef.
Note
refs passed to classes are not passed as props since they reference the component instance.
Diffs for hydration errors
We also improved error reporting for hydration errors in react-dom. For example, instead of logging multiple errors in DEV without any information about the mismatch:
Console
Warning: Text content did not match. Server: “Server” Client: “Client”
at span
at App
Warning: An error occurred during hydration. The server HTML was replaced with client content in .
Warning: Text content did not match. Server: “Server” Client: “Client”
at span
at App
Warning: An error occurred during hydration. The server HTML was replaced with client content in .
Uncaught Error: Text content does not match server-rendered HTML.
at checkForUnmatchedText
…
We now log a single message with a diff of the mismatch:
Console
Uncaught Error: Hydration failed because the server rendered HTML didn’t match the client. As a result this tree will be regenerated on the client. This can happen if an SSR-ed Client Component used:
A server/client branch if (typeof window !== 'undefined').
Variable input such as Date.now() or Math.random() which changes each time it’s called.
Date formatting in a user’s locale which doesn’t match the server.
External changing data without sending a snapshot of it along with the HTML.
Invalid HTML tag nesting.
It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
In React 19, you can render as a provider instead of <Context.Provider>:
const ThemeContext = createContext('');
function App({children}) {
return (
{children}
);
}
New Context providers can use and we will be publishing a codemod to convert existing providers. In future versions we will deprecate <Context.Provider>.
Cleanup functions for refs
We now support returning a cleanup function from ref callbacks:
<input
ref={(ref) => {
// ref created
code
// NEW: return a cleanup function to reset
// the ref when element is removed from DOM.
return () => {
// ref cleanup
};
}}
/>
When the component unmounts, React will call the cleanup function returned from the ref callback. This works for DOM refs, refs to class components, and useImperativeHandle.
Note
Previously, React would call ref functions with null when unmounting the component. If your ref returns a cleanup function, React will now skip this step.
In future versions, we will deprecate calling refs with null when unmounting components.
Due to the introduction of ref cleanup functions, returning anything else from a ref callback will now be rejected by TypeScript. The fix is usually to stop using implicit returns, for example:
The original code returned the instance of the HTMLDivElement and TypeScript wouldn’t know if this was supposed to be a cleanup function or if you didn’t want to return a cleanup function.
You can codemod this pattern with no-implicit-ref-callback-return.
useDeferredValue initial value
We’ve added an initialValue option to useDeferredValue:
function Search({deferredValue}) {
// On initial render the value is ''.
// Then a re-render is scheduled with the deferredValue.
const value = useDeferredValue(deferredValue, '');
return (
);
}
When initialValue is provided, useDeferredValue will return it as value for the initial render of the component, and schedules a re-render in the background with the deferredValue returned.
For more, see useDeferredValue.
Support for Document Metadata
In HTML, document metadata tags like , , and are reserved for placement in the section of the document. In React, the component that decides what metadata is appropriate for the app may be very far from the place where you render the or React does not render the at all. In the past, these elements would need to be inserted manually in an effect, or by libraries like react-helmet, and required careful handling when server rendering a React application.
In React 19, we’re adding support for rendering document metadata tags in components natively:
When React renders this component, it will see the and tags, and automatically hoist them to the section of document. By supporting these metadata tags natively, we’re able to ensure they work with client-only apps, streaming SSR, and Server Components.
Note
You may still want a Metadata library
For simple use cases, rendering Document Metadata as tags may be suitable, but libraries can offer more powerful features like overriding generic metadata with specific metadata based on the current route. These features make it easier for frameworks and libraries like react-helmet to support metadata tags, rather than replace them.
For more info, see the docs for , , and .
Support for stylesheets
Stylesheets, both externally linked () and inline (...), require careful positioning in the DOM due to style precedence rules. Building a stylesheet capability that allows for composability within components is hard, so users often end up either loading all of their styles far from the components that may depend on them, or they use a style library which encapsulates this complexity.
In React 19, we’re addressing this complexity and providing even deeper integration into Concurrent Rendering on the Client and Streaming Rendering on the Server with built in support for stylesheets. If you tell React the precedence of your stylesheet it will manage the insertion order of the stylesheet in the DOM and ensure that the stylesheet (if external) is loaded before revealing content that depends on those style rules.
function ComponentOne() {
return (
{...}
)
}
function ComponentTwo() {
return (
{...}
<-- will be inserted between foo & bar
)
}
During Server Side Rendering React will include the stylesheet in the , which ensures that the browser will not paint until it has loaded. If the stylesheet is discovered late after we’ve already started streaming, React will ensure that the stylesheet is inserted into the on the client before revealing the content of a Suspense boundary that depends on that stylesheet.
During Client Side Rendering React will wait for newly rendered stylesheets to load before committing the render. If you render this component from multiple places within your application React will only include the stylesheet once in the document:
function App() {
return <>
...
// won't lead to a duplicate stylesheet link in the DOM
</>
}
For users accustomed to loading stylesheets manually this is an opportunity to locate those stylesheets alongside the components that depend on them allowing for better local reasoning and an easier time ensuring you only load the stylesheets that you actually depend on.
Style libraries and style integrations with bundlers can also adopt this new capability so even if you don’t directly render your own stylesheets, you can still benefit as your tools are upgraded to use this feature.
For more details, read the docs for and .
Support for async scripts
In HTML normal scripts () and deferred scripts () load in document order which makes rendering these kinds of scripts deep within your component tree challenging. Async scripts () however will load in arbitrary order.
In React 19 we’ve included better support for async scripts by allowing you to render them anywhere in your component tree, inside the components that actually depend on the script, without having to manage relocating and deduplicating script instances.
function MyComponent() {
return (
Hello World
)
}
function App() {
In all rendering environments, async scripts will be deduplicated so that React will only load and execute the script once even if it is rendered by multiple different components.
In Server Side Rendering, async scripts will be included in the and prioritized behind more critical resources that block paint such as stylesheets, fonts, and image preloads.
For more details, read the docs for .
Support for preloading resources
During initial document load and on client side updates, telling the Browser about resources that it will likely need to load as early as possible can have a dramatic effect on page performance.
React 19 includes a number of new APIs for loading and preloading Browser resources to make it as easy as possible to build great experiences that aren’t held back by inefficient resource loading.
import { prefetchDNS, preconnect, preload, preinit } from 'react-dom'
function MyComponent() {
preinit('https://.../path/to/some/script.js', {as: 'script' }) // loads and executes this script eagerly
preload('https://.../path/to/font.woff', { as: 'font' }) // preloads this font
preload('https://.../path/to/stylesheet.css', { as: 'style' }) // preloads this stylesheet
prefetchDNS('https://...') // when you may not actually request anything from this host
preconnect('https://...') // when you will request something but aren't sure what
}
These APIs can be used to optimize initial page loads by moving discovery of additional resources like fonts out of stylesheet loading. They can also make client updates faster by prefetching a list of resources used by an anticipated navigation and then eagerly preloading those resources on click or even on hover.
For more details see Resource Preloading APIs.
Compatibility with third-party scripts and extensions
We’ve improved hydration to account for third-party scripts and browser extensions.
When hydrating, if an element that renders on the client doesn’t match the element found in the HTML from the server, React will force a client re-render to fix up the content. Previously, if an element was inserted by third-party scripts or browser extensions, it would trigger a mismatch error and client render.
In React 19, unexpected tags in the and will be skipped over, avoiding the mismatch errors. If React needs to re-render the entire document due to an unrelated hydration mismatch, it will leave in place stylesheets inserted by third-party scripts and browser extensions.
Better error reporting
We improved error handling in React 19 to remove duplication and provide options for handling caught and uncaught errors. For example, when there’s an error in render caught by an Error Boundary, previously React would throw the error twice (once for the original error, then again after failing to automatically recover), and then call console.error with info about where the error occurred.
This resulted in three errors for every caught error:
Console
Uncaught Error: hit
at Throws
at renderWithHooks
…
Uncaught Error: hit <-- Duplicate
at Throws
at renderWithHooks
…
The above error occurred in the Throws component:
at Throws
at ErrorBoundary
at App
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
In React 19, we log a single error with all the error information included:
Console
Error: hit
at Throws
at renderWithHooks
…
The above error occurred in the Throws component:
at Throws
at ErrorBoundary
at App
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
at ErrorBoundary
at App
Additionally, we’ve added two new root options to complement onRecoverableError:
code
onCaughtError: called when React catches an error in an Error Boundary.
onUncaughtError: called when an error is thrown and not caught by an Error Boundary.
onRecoverableError: called when an error is thrown and automatically recovered.
To address the issues you're encountering in your React component—specifically the useCallback warning, the unwanted exit animation, and performance optimizations—let's break down each concern and provide comprehensive solutions. Additionally, we'll ensure compatibility with React 19 and Next.js 15.
1. Fixing the useCallback Warning
Warning Message:
code
62:29 Warning: React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead. react-hooks/exhaustive-deps
This warning typically arises when the dependencies of a useCallback hook are not properly specified, leading to potential stale references or unexpected behaviors.
Solution:
Review Dependencies:
Ensure that all variables and functions used inside the useCallback are declared in the dependency array.
For functions like fetchBestSelling and updateRecentSearches, verify that they're only dependent on stable references or include all necessary dependencies.
Refactor debouncedSearch:
Wrapping a debounced function inside useCallback can sometimes lead to unexpected dependencies.
Instead, use useMemo to memoize the debounced function, ensuring it's only created once.
Code Adjustments:
Here's the revised code with proper dependency management:
updateRecentSearches: Removed recentSearches from dependencies by utilizing the functional form of setRecentSearches. This ensures that the latest state is always used without needing to include it in the dependency array.
debouncedSearch: Changed from useCallback to useMemo since we're memoizing a debounced function. This prevents recreating the debounced function on every render and ensures proper cleanup.
renderSearchItem: Wrapped with useCallback to memoize the function, preventing unnecessary re-creations and re-renders.
Cleanup: Ensured that the debounced function is canceled on component unmount to prevent memory leaks.
2. Removing Unwanted Exit Animation
You want the dropdown to disappear immediately without any animation when the input loses focus. To achieve this, we'll adjust the AnimatePresence and motion.div configurations.
Solution:
Differentiate Entry and Exit Animations:
Keep the entry animation for a smooth appearance.
Remove or minimize the exit animation to make the dropdown disappear instantly.
Adjust Transition Durations:
Set the exit transition duration to 0ms to eliminate the animation.
Code Adjustments:
Modify the dropdownVariants and the motion.div responsible for the dropdown:
javascript
// Animation variants for the dropdown
const dropdownVariants = {
hidden: { opacity: 0, scale: 0.95 },
visible: { opacity: 1, scale: 1 },
// Remove or adjust the exit variant
exit: { opacity: 0, scale: 1 }, // Scale remains the same for instant disappearance
};
// In the dropdown motion.div
<motion.div
variants={dropdownVariants}
initial="hidden"
animate="visible"
exit="exit"
transition={{ duration: 0.2, ease: 'easeOut' }} // Keep entry animation
className="absolute z-10 w-full mt-1 rounded-md bg-white shadow-lg max-h-96 overflow-y-auto"
>
{/* ... */}
</motion.div>
Alternative Approach:
If you prefer to have no animation on exit, you can conditionally apply animations based on whether the component is entering or exiting.
Avoid Redundant States: Ensure that states like hasMore are derived from API responses and not unnecessarily managed elsewhere.
**c. Optimize Debouncing
Ensure that the debounced function is not recreated on every render, which we've addressed earlier by using useMemo.
**d. Avoid Inline Functions in JSX
Inline functions can cause re-renders because they are recreated on each render. By memoizing them using useCallback, we prevent unnecessary re-renders.
Use Next.js's next/image component effectively by enabling lazy loading to improve performance.
javascript
<Image
src={`https://storage.naayiq.com/resources/${item.images[0].url}`}
alt={item.name}
width={40}
height={40}
className="object-cover rounded"
loading="lazy" // Ensures images are loaded only when in viewport
/>
**f. Proper Error Handling
Ensure all fetch requests have robust error handling to prevent the app from crashing.
javascript
catch (error) {
console.error('Error fetching data:', error);
// Optionally set an error state to inform users
}
4. Ensuring Compatibility with React 19 and Next.js 15
While React 19 is still in its early stages (as per the latest knowledge cutoff), it's essential to follow best practices to ensure compatibility:
**a. Use Stable APIs
Stick to using stable React and Next.js APIs unless you're certain about the experimental features in React 19.
**b. Leverage New React Features Wisely
If you wish to utilize React 19's new features like useActionState or useOptimistic, ensure they align with your project's requirements and are stable enough for production.
**c. Update Dependencies
Ensure all your dependencies, especially framer-motion, lodash, and next, are compatible with React 19. Check their documentation for any required updates or compatibility notes.
**d. Test Across Environments
Development & Production Builds: Ensure that your component works seamlessly in both development and production builds.
Different Browsers: Test the component across various browsers to ensure consistent behavior.
**e. Server-Side Rendering (SSR) Considerations
Since you're using Next.js, ensure that your component behaves correctly with SSR:
Avoid using browser-specific APIs directly; use them within useEffect to ensure they only run on the client-side.
Ensure that data fetching aligns with Next.js's data fetching methods (getServerSideProps, getStaticProps, etc.) if applicable.
5. Final Optimized Code
Here's the complete optimized version of your ProductSearchComponent incorporating all the above recommendations:
javascript
6. Additional Recommendations
**a. Accessibility Enhancements
Keyboard Navigation: Ensure that users can navigate through search results using the keyboard (e.g., arrow keys, enter key).
ARIA Attributes: Use appropriate ARIA attributes to improve screen reader compatibility.
Unit Tests: Write unit tests for individual functions and components using tools like Jest and React Testing Library.
Integration Tests: Ensure that the component interacts correctly with APIs and handles various states (loading, error, success).
7. Leveraging React 19 Features (Optional)
While React 19 introduces several new features, such as useActionState, useOptimistic, and enhancements to server actions, integrating them into your component depends on your specific requirements. Here's a brief overview of how some of these could potentially be utilized:
**a. Using useActionState for Form Handling
If you plan to handle more complex form submissions or data mutations, useActionState can simplify state management.
Note: These integrations are optional and should be considered based on the complexity and requirements of your application.
8. Conclusion
By meticulously addressing the useCallback warnings, adjusting exit animations, and implementing performance optimizations, your ProductSearchComponent will become more robust, user-friendly, and maintainable. Additionally, adhering to React and Next.js best practices ensures compatibility and prepares your application for future enhancements, including the features introduced in React 19.
Feel free to further customize and enhance the component based on your specific use cases and user feedback.