Skip to content

🪝 React hook for subscribing to user's motion preference.

License

Notifications You must be signed in to change notification settings

anatoliygatt/use-prefers-reduced-motion

Repository files navigation


use-prefers-reduced-motion Logo

use-prefers-reduced-motion

React hook for subscribing to user's motion preference.


Github CI Workflow Status NPM Version License


🚀 Getting Started

⚡️ Quick Start

npm install @anatoliygatt/use-prefers-reduced-motion
import { usePrefersReducedMotion } from '@anatoliygatt/use-prefers-reduced-motion';

function Example() {
  const prefersReducedMotion = usePrefersReducedMotion();
  return (
    <div
      className={`box ${
        prefersReducedMotion ? 'fade-in' : 'fade-in-and-scale-up'
      }`}
    />
  );
}

💻 Live Demo

Open in CodeSandbox

⚙️ Usage with Server Side Rendering (SSR)

Frameworks like Next.js and Gatsby take advantage of server-side rendering, which means that the HTML is pre-rendered at some point before it's sent to the browser. When we first render our React component tree, we don't know whether the user prefers reduced motion or not.

It may lead to the markup mismatches during hydration. In order to prevent this, we need to set the ssr option provided by the usePrefersReducedMotion() hook to true, like so:

usePrefersReducedMotion({ ssr: true });

This will guarantee no markup mismatches between the original server render and the first client render, however, we will have to make a compromise: reduce motion of our animations for all users in the very first render.

👨🏼‍⚖️ License

MIT