Skip to content

Commit 0317eae

Browse files
authored
23630: Added hooks to support browser prefers-reduced-motion preferences, MINOR (#97)
1 parent 1e54910 commit 0317eae

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/hooks/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from "./useColorSchemePreference";
22
export * from "./useFloating";
33
export * from "./useFormValues";
4+
export * from "./useReducedMotionPreference";
45
export * from "./useWindowSize";
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { useEffect, useRef, useState } from "react";
2+
3+
/** Provides the user's reduced motion preference and subscribes to changes. */
4+
export const useReducedMotionPreference = (): boolean => {
5+
const match = useRef<MediaQueryList>(
6+
window.matchMedia("(prefers-reduced-motion: reduce)"),
7+
);
8+
const [isReducedPreferred, setIsReducedPreferred] = useState(
9+
!!match.current.matches,
10+
);
11+
12+
useEffect(() => {
13+
const currentMatch = match.current;
14+
const onChange = () => {
15+
setIsReducedPreferred(!!currentMatch.matches);
16+
};
17+
18+
currentMatch.addEventListener("change", onChange);
19+
return () => currentMatch.removeEventListener("change", onChange);
20+
}, [match]);
21+
22+
return isReducedPreferred;
23+
};
24+
25+
/** Returns the 'smooth' behavior, unless the user's preference is prefers-reduced-motion: 'reduce' */
26+
export const useScrollBehaviorPreference = (): ScrollBehavior | undefined => {
27+
const isReducedMotionPreferred = useReducedMotionPreference();
28+
return !isReducedMotionPreferred ? "smooth" : undefined;
29+
};

0 commit comments

Comments
 (0)