From 076da5381559fdd6f2e5b6749bfa03eaa3ff084c Mon Sep 17 00:00:00 2001 From: Jamie Kyle <113370520+jamiebuilds-signal@users.noreply.github.com> Date: Fri, 4 Aug 2023 08:17:12 -0700 Subject: [PATCH] Refactor useReducedMotion --- ts/hooks/useReducedMotion.ts | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/ts/hooks/useReducedMotion.ts b/ts/hooks/useReducedMotion.ts index b1fdb3da9aa3..fd9f81822250 100644 --- a/ts/hooks/useReducedMotion.ts +++ b/ts/hooks/useReducedMotion.ts @@ -3,32 +3,25 @@ import { useEffect, useState } from 'react'; -function getReducedMotionQuery(): MediaQueryList { - return window.matchMedia('(prefers-reduced-motion: reduce)'); +// Allows this to work in Node process +let reducedMotionQuery: MediaQueryList; +function getReducedMotionQuery() { + if (reducedMotionQuery == null) { + reducedMotionQuery = window.matchMedia('(prefers-reduced-motion)'); + } + return reducedMotionQuery; } -// Inspired by . export function useReducedMotion(): boolean { - const initialQuery = getReducedMotionQuery(); - const [prefersReducedMotion, setPrefersReducedMotion] = useState( - initialQuery.matches - ); - + const [matches, setMatches] = useState(getReducedMotionQuery().matches); useEffect(() => { - const query = getReducedMotionQuery(); - - function changePreference() { - setPrefersReducedMotion(query.matches); + function onChange(event: MediaQueryListEvent) { + setMatches(event.matches); } - - changePreference(); - - query.addEventListener('change', changePreference); - + getReducedMotionQuery().addEventListener('change', onChange); return () => { - query.removeEventListener('change', changePreference); + getReducedMotionQuery().removeEventListener('change', onChange); }; - }); - - return prefersReducedMotion; + }, []); + return matches; }