Skip to content

Commit 2a93ad0

Browse files
committed
fix: color scheme queries in usememo
1 parent 4c40105 commit 2a93ad0

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

packages/react/src/hooks/usePrefersColorScheme.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@
22
// https://github.com/rfoel/use-prefers-color-scheme/blob/v1.0.0/src/index.ts
33
// The code is copied instead of being imported as the package seems to cause
44
// issues when used in a NextJS project.
5-
import { useEffect, useState } from "react";
6-
7-
const darkQuery = window?.matchMedia?.("(prefers-color-scheme: dark)");
8-
9-
const lightQuery = window?.matchMedia?.("(prefers-color-scheme: light)");
5+
import { useEffect, useMemo, useState } from "react";
106

117
export const usePrefersColorScheme = () => {
8+
const darkQuery = useMemo(
9+
() => window.matchMedia?.("(prefers-color-scheme: dark)"),
10+
[]
11+
);
12+
const lightQuery = useMemo(
13+
() => window.matchMedia?.("(prefers-color-scheme: light)"),
14+
[]
15+
);
1216
const isDark = darkQuery?.matches;
1317
const isLight = lightQuery?.matches;
1418

@@ -69,9 +73,9 @@ export const usePrefersColorScheme = () => {
6973
lightQuery?.removeEventListener("change", listener);
7074
};
7175
}
72-
}, []);
76+
}, [darkQuery, lightQuery]);
7377

74-
if (typeof window?.matchMedia !== "function") {
78+
if (typeof window.matchMedia !== "function") {
7579
return preferredColorSchema;
7680
}
7781

0 commit comments

Comments
 (0)