BrowserBeginnerSSR-safehooks/browser/useWindowSize.ts

useWindowSize

SSR-safe window size.

Import

TypeScript
import { useWindowSize } from '@/hooks';

API

Signature

useWindowSize() → { width, height }

When to use

Use useWindowSize instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Returns defaults on the server; hydrates on the client.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useWindowSize
Editor
function Size() {
  const { width, height } = useWindowSize();
  return <p>{width} × {height}</p>;
}
Preview

Implementation source

Full library source for useWindowSize — copy into your project when you are not installing a package yet.

hooks/browser/useWindowSize.ts
import { useCallback, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
import { useEventListener } from '../events/useEventListener';

export interface WindowSize {
  width: number;
  height: number;
}

function readSize(): WindowSize {
  if (!isBrowser()) return { width: 0, height: 0 };
  return { width: window.innerWidth, height: window.innerHeight };
}

/** SSR-safe window inner dimensions. */
export function useWindowSize(): WindowSize {
  const [size, setSize] = useState<WindowSize>(() =>
    isBrowser() ? readSize() : { width: 0, height: 0 },
  );

  const update = useCallback(() => setSize(readSize()), []);

  useIsomorphicLayoutEffect(() => {
    update();
  }, [update]);

  useEventListener('resize', update);

  return size;
}

Copy-paste example

useWindowSize.example.tsx
'use client';

import { useWindowSize } from '@/hooks';

export function Size() {
  const { width, height } = useWindowSize();
  return <p>{width} × {height}</p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
  • Source of truth: open hooks/browser/useWindowSize.ts for implementation details