Files
outline/app/hooks/useWindowSize.ts
Tom MoorandClaude Opus 4.8 0a90968d97 Adopt React 19 hooks for browser-state and client-side filters (#13844)
* refactor: Adopt React 19 browser-state and filter hooks

Rewrite browser-state hooks with useSyncExternalStore, adopt
useEffectEvent for latest-ref patterns, and defer client-side
filters with useDeferredValue.

* fix: Refresh usePersistedState default when key changes

* fix: Normalize serialized cache key for undefined values

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* iterate

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-23 19:11:29 -04:00

46 lines
1.5 KiB
TypeScript

import { throttle } from "es-toolkit/compat";
import { useCallback, useRef, useSyncExternalStore } from "react";
type WindowSize = { width: number; height: number };
const readSize = (): WindowSize => ({
width: window.visualViewport?.width || window.innerWidth,
height: window.visualViewport?.height || window.innerHeight,
});
/**
* A throttled hook that listens to the window resize event and returns the
* size of the current window.
*
* @returns An object containing width and height of the current window
*/
export default function useWindowSize(): WindowSize {
// Cache the last object so getSnapshot returns a stable reference while the
// size is unchanged, which useSyncExternalStore requires.
const cache = useRef<WindowSize>(readSize());
const getSnapshot = useCallback(() => {
const next = readSize();
if (
next.width !== cache.current.width ||
next.height !== cache.current.height
) {
cache.current = next;
}
return cache.current;
}, []);
const subscribe = useCallback((onStoreChange: () => void) => {
const handleResize = throttle(onStoreChange, 100);
window.addEventListener("resize", handleResize);
window.visualViewport?.addEventListener("resize", handleResize);
return () => {
handleResize.cancel();
window.removeEventListener("resize", handleResize);
window.visualViewport?.removeEventListener("resize", handleResize);
};
}, []);
return useSyncExternalStore(subscribe, getSnapshot);
}