Snippet

usePrefersReducedMotion

js

For some people, motion can be harmful.

The prefers-reduced-motion CSS media query allows us to disable animations for these folks. For our animations that are entirely in CSS (eg. CSS transitions, CSS keyframe animations), this works great 💯

What about for our animations in JavaScript, though? For example, when we use a library like React Spring or Framer Motion? We need to manage it ourselves, and it becomes a pretty tricky endeavour.

For these cases, I created a use-prefers-reduced-motion hook.

I wrote a blog post all about this:

Link to this heading
Listening for changes

For the best possible user experience, we want to re-render components that rely on this hook when the user toggles prefers-reduced-motion on or off.

In older browsers, this is done with mediaQueryList.addListener(...). This syntax has been updated in newer browsers to be a bit more conventional: mediaQueryList.addEventListener('change', ...).

To make sure we support as many browsers as possible, we'll use both.

Link to this heading
With React Spring

jsx
Last Updated:
October 6th, 2021