useViewTransition
Use the View Transitions API for smooth page animations.
useViewTransition
The useViewTransition hook provides access to the View Transitions API for smooth animated transitions between page states. It gracefully falls back in unsupported browsers.
Usage
import { useViewTransition } from '@/hooks';
import { useRouter } from 'next/navigation';
function NavigationLink({ href, children }) {
const router = useRouter();
const { startTransition, isSupported } = useViewTransition();
const handleClick = (e: MouseEvent) => {
e.preventDefault();
startTransition(() => {
router.push(href);
});
};
return (
<a href={href} onClick={handleClick}>
{children}
</a>
);
}
API
function useViewTransition(): {
startTransition: (callback: () => void | Promise<void>) => void;
isSupported: boolean;
}
Return Values
| Property | Type | Description |
|---|---|---|
startTransition | function | Wraps DOM changes in a view transition |
isSupported | boolean | Whether the API is available |
Browser Support
The View Transitions API is supported in Chrome 111+, Edge 111+, and Opera 97+. Safari and Firefox are working on implementation.
The hook automatically falls back to executing the callback directly in unsupported browsers.
CSS Customization
Control the transition animation with CSS:
/* Customize transition timing */
::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 0.3s;
}
/* Crossfade effect */
::view-transition-old(root) {
animation: fade-out 0.3s ease-out;
}
::view-transition-new(root) {
animation: fade-in 0.3s ease-in;
}