Skip to content

Instantly share code, notes, and snippets.

@olibooty
Last active May 20, 2025 15:11
Show Gist options
  • Select an option

  • Save olibooty/f1419a4df09e7de0e173e8221c4101d9 to your computer and use it in GitHub Desktop.

Select an option

Save olibooty/f1419a4df09e7de0e173e8221c4101d9 to your computer and use it in GitHub Desktop.
useWindowSize.ts
import { useSyncExternalStore } from "react";
function subscribe(onStoreChange: () => void) {
console.log("called");
window.addEventListener("resize", onStoreChange);
return () => window.removeEventListener("resize", onStoreChange);
}
function getServerSnapshot() {
return 0;
}
function getWindowWidthSnapshot() {
return window.innerWidth;
}
function getWindowHeightSnapshot() {
return window.innerHeight;
}
function getWindowScreenWidthSnapshot() {
return window.screen.width;
}
function getWindowScreenHeightSnapshot() {
return window.screen.height;
}
function useSyncWindowStore<T>(getSnapshot: () => T) {
const store = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
return store;
}
export function useWindowSize() {
const width = useSyncWindowStore(getWindowWidthSnapshot);
const height = useSyncWindowStore(getWindowHeightSnapshot);
const screenW = useSyncWindowStore(getWindowScreenWidthSnapshot);
const screenH = useSyncWindowStore(getWindowScreenHeightSnapshot);
return {
width,
height,
screen: {
width: screenW,
height: screenH,
},
};
}
import { useSyncExternalStore } from "react";
function subscribe(onStoreChange: () => void) {
console.log("called");
window.addEventListener("resize", onStoreChange);
return () => window.removeEventListener("resize", onStoreChange);
}
function getServerSnapshot() {
return 0;
}
function getWindowWidthSnapshot() {
return window.innerWidth;
}
function getWindowHeightSnapshot() {
return window.innerHeight;
}
function getWindowScreenWidthSnapshot() {
return window.screen.width;
}
function getWindowScreenHeightSnapshot() {
return window.screen.height;
}
function useWindowWidth() {
const store = useSyncExternalStore(
subscribe,
getWindowWidthSnapshot,
getServerSnapshot
);
return store;
}
function useWindowHeight() {
const store = useSyncExternalStore(
subscribe,
getWindowHeightSnapshot,
getServerSnapshot
);
return store;
}
function useWindowScreenWidth() {
const store = useSyncExternalStore(
subscribe,
getWindowScreenWidthSnapshot,
getServerSnapshot
);
return store;
}
function useWindowScreenHeight() {
const store = useSyncExternalStore(
subscribe,
getWindowScreenHeightSnapshot,
getServerSnapshot
);
return store;
}
export function useWindowSize() {
const width = useWindowWidth();
const height = useWindowHeight();
const screenW = useWindowScreenWidth();
const screenH = useWindowScreenHeight();
return {
width,
height,
screen: {
width: screenW,
height: screenH,
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment