MCPcopy Index your code
hub / github.com/streamich/react-use / useWindowSize

Function useWindowSize

src/useWindowSize.ts:13–53  ·  view source on GitHub ↗
({
  initialWidth = Infinity,
  initialHeight = Infinity,
  onChange,
}: Options = {})

Source from the content-addressed store, hash-verified

11}
12
13const useWindowSize = ({
14 initialWidth = Infinity,
15 initialHeight = Infinity,
16 onChange,
17}: Options = {}) => {
18 // Use the useRafState hook to maintain the current window size (width and height)
19 const [state, setState] = useRafState<{ width: number; height: number }>({
20 width: isBrowser ? window.innerWidth : initialWidth,
21 height: isBrowser ? window.innerHeight : initialHeight,
22 });
23
24 useEffect((): (() => void) | void => {
25 // Only run the effect on the browser (to avoid issues with SSR)
26 if (isBrowser) {
27 const handler = () => {
28 const width = window.innerWidth;
29 const height = window.innerHeight;
30
31 // Update the state with the new window size
32 setState({
33 width,
34 height,
35 });
36
37 // If an onChange callback is provided, call it with the new dimensions
38 if (onChange) onChange(width, height);
39 };
40
41 // Add event listener for the resize event
42 on(window, 'resize', handler);
43
44 // Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization)
45 return () => {
46 off(window, 'resize', handler);
47 };
48 }
49 }, []);
50
51 // Return the current window size (width and height)
52 return state;
53};
54
55export default useWindowSize;

Callers 2

DemoFunction · 0.90
getHookFunction · 0.85

Calls 3

onFunction · 0.90
offFunction · 0.90
useRafStateFunction · 0.85

Tested by 1

getHookFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…