Skip to content

Instantly share code, notes, and snippets.

@vanaf1979
Last active February 19, 2023 14:52
Show Gist options
  • Save vanaf1979/f5e680f6b947d92703a52b592d244a8a to your computer and use it in GitHub Desktop.
Save vanaf1979/f5e680f6b947d92703a52b592d244a8a to your computer and use it in GitHub Desktop.
import { useState, useEffect } from "react";
const useReducedMotion = (defaultVal = true) => {
// Local state to store the reduced motion setting.
const [reducedMotion, setReducedMotion] = useState(defaultVal);
// Callback for media query cahnge events.
function queryCnangeHandler(event) {
// Set the state to the value of the media query.
setReducedMotion(event.target.matches);
}
useEffect(() => {
// Grab the reduced motion media query,
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
if(mediaQuery) {
// Set the state to the value of the media query.
setReducedMotion(mediaQuery.matches);
// Lissten for changes in the media query.
mediaQuery.addEventListener("change", queryCnangeHandler);
// Remove the event listener when the component unmounts.
return () => mediaQuery.removeEventListener("change", queryCnangeHandler);
}
}, []);
return reducedMotion;
};
export default useReducedMotion;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment