BrowserBeginnerSSR-safehooks/browser/useScreenSize.ts

useScreenSize

window.screen dimensions.

Import

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

API

Signature

useScreenSize() → { width, height, availWidth, availHeight }

When to use

Use useScreenSize 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 · useScreenSize
Editor
function Screen() {
  const s = useScreenSize();
  return <p>screen {s.width}×{s.height}</p>;
}
Preview

Implementation source

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

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

export interface ScreenSize {
  width: number;
  height: number;
  availWidth: number;
  availHeight: number;
}

function readScreen(): ScreenSize {
  if (!isBrowser()) {
    return { width: 0, height: 0, availWidth: 0, availHeight: 0 };
  }
  return {
    width: window.screen.width,
    height: window.screen.height,
    availWidth: window.screen.availWidth,
    availHeight: window.screen.availHeight,
  };
}

/** SSR-safe `window.screen` dimensions. */
export function useScreenSize(): ScreenSize {
  const [size, setSize] = useState(readScreen);
  const update = useCallback(() => setSize(readScreen()), []);
  useIsomorphicLayoutEffect(() => {
    update();
  }, [update]);
  useEventListener('resize', update);
  return size;
}

Copy-paste example

useScreenSize.example.tsx
'use client';

import { useScreenSize } from '@/hooks';

export function Screen() {
  const s = useScreenSize();
  return <p>screen {s.width}×{s.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/useScreenSize.ts for implementation details