Skip to content

Instantly share code, notes, and snippets.

Last active Aug 17, 2021
What would you like to do?
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.
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.
// 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