Refactor useReducedMotion

This commit is contained in:
Jamie Kyle 2023-08-04 08:17:12 -07:00 committed by GitHub
parent 6d16fdcd16
commit 076da53815
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -3,32 +3,25 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
function getReducedMotionQuery(): MediaQueryList { // Allows this to work in Node process
return window.matchMedia('(prefers-reduced-motion: reduce)'); let reducedMotionQuery: MediaQueryList;
function getReducedMotionQuery() {
if (reducedMotionQuery == null) {
reducedMotionQuery = window.matchMedia('(prefers-reduced-motion)');
}
return reducedMotionQuery;
} }
// Inspired by <https://github.com/infiniteluke/react-reduce-motion>.
export function useReducedMotion(): boolean { export function useReducedMotion(): boolean {
const initialQuery = getReducedMotionQuery(); const [matches, setMatches] = useState(getReducedMotionQuery().matches);
const [prefersReducedMotion, setPrefersReducedMotion] = useState(
initialQuery.matches
);
useEffect(() => { useEffect(() => {
const query = getReducedMotionQuery(); function onChange(event: MediaQueryListEvent) {
setMatches(event.matches);
function changePreference() {
setPrefersReducedMotion(query.matches);
} }
getReducedMotionQuery().addEventListener('change', onChange);
changePreference();
query.addEventListener('change', changePreference);
return () => { return () => {
query.removeEventListener('change', changePreference); getReducedMotionQuery().removeEventListener('change', onChange);
}; };
}); }, []);
return matches;
return prefersReducedMotion;
} }