Today I Learned

hashrocket A Hashrocket project

Use reduced motion to control a video

I used my useWatchMedia hook to play/pause a video based on the reduced motion OS config.

On Macs you can set this option in System Preferences => Accessibility => Display:

image

This way users with motion sickness can have better time browsing your website.

And here's my video component:

const useReducedMotion = () => {
  return useWatchMedia('(prefers-reduced-motion: reduce)');
};
const MyVideo = ({url}) => {
  const ref = useRef();
  const reducedMotion = useReducedMotion();

  useLayoutEffect(() => {
    if (ref.current) {
      reducedMotion ? ref.current.pause() : ref.current.play();
    }
  }, [ref, reducedMotion]);

  return (
    <video autoPlay loop muted playsInline ref={ref} src={url} />
  );
};

As the browser exposes this config via media query we could also use regular css for that media to enable/disable features, for example css animations.

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.