npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-view-transitions

v1.0.16

Published

A React hook for CSS view transitions

Downloads

1,172

Readme

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