Skip to content

noamr/use-view-transitions

Repository files navigation

Using CSS same-document view-transitions with React

Installation

npm install use-view-transitions

Overview

CSS view transitions are a new feature that allows for expressive animations between states.

The main syntax for view-transitions looks something like this:

document.startViewTransition(() => updateDOMAndReturnPromise())

There are several ways to use this API in a React or NextJS single-page app.

React

Using flushSync

This is the most basic way, and it doesn't require too much magic.

document.startViewTransition(() =>
	ReactDOM.flushSync(() => {
		// set the "after" state here, synchronously.
	}),
)

This approach should work for the common cases, but some apps don't work well with synchronous updates. For example, some components might rely on some fast asynchronous work to display correctly. When using flushSync, any asynchronous work would be rendered after the transition is complete.

The useViewTransition hook

This hook would work for asynchronous operations, and would work without flushSync out of the box. By default, it works like React.startTransition, but would execute the CSS view-transition without a flushSync:

import { useViewTransition } from 'use-view-transitions/react'

const { startViewTransition } = useViewTransition()
const [value, increment] = useReducer((x) => x + 1, 0)
return (
	<>
		<button onClick={() => startViewTransition(() => increment())}>
			Increment
		</button>
		{value}
	</>
)

Using useViewTrantision together with the <SuspendViewTransitions /> component, you can suspend capturing the new state until ready.

import {
	useViewTransition,
	SuspendViewTransition,
} from 'use-view-transitions/react'
const { startViewTransition } = useViewTransition()
const [isLoading, setLoading] = useState(false)

// Don't use this code for real, it's simulation for something that loads asynchronously.
useEffect(() => {
	if (isLoading) {
		setTimeout(() => {
			setLoading(false)
		}, 100)
	}
}, [isLoading])

return (
	<>
		<button
			onClick={() =>
				startViewTransition(() => {
					setLoading(true)
				})
			}
		>
			Load
		</button>
		{
			// This would suspend capturing the "new" state of the transition until loaded.
			isLoading ? <SuspendViewTransition /> : null
		}
	</>
)

Note that like in the flushSync case, unrelated changes wrapped in React.startTransition would only execute as part of capturing the new state.

NextJS

Since NextJS is based on React, using the above technique would work in most cases. However, some state changes and event handlers happen within NextJS itself, e.g. navigating to routes based on link clicks.

Before AppRouter (pages directory)

For that, we offer the useNextRouterViewTransitions() hook:

// _app.js

import { useNextRouterViewTransitions } from 'use-view-transitions/next'

useNextRouterViewTransitions()

return (
	<Layout>
		<Component {...pageProps} />
	</Layout>
)

The hook listens to NextJS's router events and uses the React hook internally to make sure that the old state is captured before the navigation is executed.

With AppRouter

With AppRouter, we don't have router events, so there's no good signal of when a navigation starts. We can still use usePathname and useSearchParams to understand when a navigation is completed, but we have to do something to make sure the old state is capture before we start the navigation.

For that, we could either implement our own <Link> element, wrap the existing one, or capture clicks - which is what AutoViewTransitionsOnClick does. (Any of these ways is legit and has trade-offs).

Example:

"use client";
import {AutoViewTransitionsOnClick, EnableNextAppRouterViewTransitions} from "use-view-transitions/next";

export default function RootLayout({
  children,
}) {

  return (
    <html lang="en">
      // This would make sure transition's new state is captured at the end of the route change.
      <EnableRouterViewTransitions />

      // This captures link clicks and injects a view transition.
      <AutoViewTransitionsOnClick match="a[href]" />
      <body>
        {children}
      </body>
    </html>
  )
}

Examples