Refactor useReducedMotion
This commit is contained in:
parent
6d16fdcd16
commit
076da53815
1 changed files with 14 additions and 21 deletions
|
@ -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;
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue