You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I know this can be done with useMediaQuery, but just like useDarkMode, this would be a shortcut. It's an important one for when an application requires a switch through javascript in some way, rather than css, to enable or disable animations.
I've already written one. This one is SSR- and unittest-safe.
import{useEffect,useState}from'react';constquery='(prefers-reduced-motion: no-preference)';constusePrefersReducedMotion=(): boolean=>{// Default to no-animations, since we don't know what the// user's preference is on the server.const[prefersReducedMotion,setPrefersReducedMotion]=useState<boolean>(true);useEffect(()=>{if(!window.matchMedia){// Doesn't exist during unittestingreturnundefined;}constmediaQueryList=window.matchMedia(query);// Set the true initial value, now that we're on the client:setPrefersReducedMotion(!window.matchMedia(query).matches);// Register our event listenerconstlistener=(event: MediaQueryListEvent): void=>{setPrefersReducedMotion(!event.matches);};mediaQueryList.addEventListener('change',listener);return()=>{mediaQueryList.removeEventListener('change',listener);};},[]);returnprefersReducedMotion;};exportdefaultusePrefersReducedMotion;
This discussion was converted from issue #327 on January 07, 2024 19:39.
Heading
Bold
Italic
Quote
Code
Link
Numbered list
Unordered list
Task list
Attach files
Mention
Reference
Menu
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I know this can be done with
useMediaQuery
, but just likeuseDarkMode
, this would be a shortcut. It's an important one for when an application requires a switch through javascript in some way, rather than css, to enable or disable animations.I've already written one. This one is SSR- and unittest-safe.
Credit goes to this article by Josh Comeau, I just expanded on it a little by adding typings, mostly.
Beta Was this translation helpful? Give feedback.
All reactions