Skip to content

Commit 8f3af9b

Browse files
committed
Migrate useVisibilityChange to use uSES
1 parent 69e15d4 commit 8f3af9b

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

index.js

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1144,27 +1144,30 @@ export function useToggle(initialValue) {
11441144
return [on, handleToggle];
11451145
}
11461146

1147-
export function useVisibilityChange() {
1148-
const [documentVisible, setDocumentVisibility] = React.useState(true);
1147+
const useVisibilityChangeSubscribe = (callback) => {
1148+
document.addEventListener("visibilitychange", callback);
11491149

1150-
React.useEffect(() => {
1151-
const handleChange = () => {
1152-
if (document.visibilityState !== "visible") {
1153-
setDocumentVisibility(false);
1154-
} else {
1155-
setDocumentVisibility(true);
1156-
}
1157-
};
1158-
handleChange();
1150+
return () => {
1151+
document.removeEventListener("visibilitychange", callback);
1152+
};
1153+
};
11591154

1160-
document.addEventListener("visibilitychange", handleChange);
1155+
const getVisibilityChangeSnapshot = () => {
1156+
return document.visibilityState;
1157+
};
11611158

1162-
return () => {
1163-
document.removeEventListener("visibilitychange", handleChange);
1164-
};
1165-
}, []);
1159+
const getVisibilityChangeServerSnapshot = () => {
1160+
throw Error("useVisibilityChange is a client-only hook");
1161+
};
1162+
1163+
export function useVisibilityChange() {
1164+
const visibilityState = React.useSyncExternalStore(
1165+
useVisibilityChangeSubscribe,
1166+
getVisibilityChangeSnapshot,
1167+
getVisibilityChangeServerSnapshot
1168+
);
11661169

1167-
return documentVisible;
1170+
return visibilityState === "visible";
11681171
}
11691172

11701173
export function useWindowScroll() {

0 commit comments

Comments
 (0)