Skip to main content

Overview

The useWindow hook provides a simple abstraction for accessing the global window object in React components. This hook is primarily used internally by other hooks in the library to ensure safe window access.

Signature

const useWindow = (): Window & typeof globalThis

Parameters

This hook takes no parameters.

Return Value

Returns the global window object.

Usage

Basic Example

import { useWindow } from './hooks/use-window';

function WindowInfo() {
  const window = useWindow();

  return (
    <div>
      <p>Width: {window.innerWidth}px</p>
      <p>Height: {window.innerHeight}px</p>
    </div>
  );
}

Accessing Window Properties

import { useWindow } from './hooks/use-window';
import { useEffect } from 'react';

function ScrollTracker() {
  const window = useWindow();

  useEffect(() => {
    const handleScroll = () => {
      console.log('Scroll position:', window.scrollY);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [window]);

  return <div>Scroll the page to see console logs</div>;
}

Using Window APIs

import { useWindow } from './hooks/use-window';

function LocationInfo() {
  const window = useWindow();
  const url = window.location.href;
  const hostname = window.location.hostname;

  return (
    <div>
      <p>Current URL: {url}</p>
      <p>Hostname: {hostname}</p>
    </div>
  );
}

Checking Browser Features

import { useWindow } from './hooks/use-window';

function FeatureDetection() {
  const window = useWindow();

  const hasLocalStorage = () => {
    try {
      return 'localStorage' in window && window.localStorage !== null;
    } catch {
      return false;
    }
  };

  const hasGeolocation = 'geolocation' in window.navigator;
  const hasServiceWorker = 'serviceWorker' in window.navigator;

  return (
    <div>
      <p>LocalStorage: {hasLocalStorage() ? 'Available' : 'Not available'}</p>
      <p>Geolocation: {hasGeolocation ? 'Available' : 'Not available'}</p>
      <p>Service Worker: {hasServiceWorker ? 'Available' : 'Not available'}</p>
    </div>
  );
}

Use Cases

  • Internal Hook Usage: Used by useLocalStorage and useMatchMedia hooks
  • Window Event Listeners: Safe access when adding window event listeners
  • Browser APIs: Accessing window-specific APIs like localStorage, sessionStorage, or location
  • Feature Detection: Checking for browser capabilities
  • Window Properties: Reading viewport dimensions or scroll position
  • Testing: Provides a single point for mocking window in tests

Implementation Details

  • Returns the global window object directly
  • Provides a consistent API for accessing window across components
  • Serves as a centralized access point for window-related operations
  • Makes testing easier by providing a single hook to mock

Why Use This Hook?

While this hook simply returns the window object, it offers several benefits:
  1. Consistency: Provides a uniform way to access window across the codebase
  2. Testability: Makes it easier to mock window in unit tests
  3. Abstraction: Creates a single point of access for window-related operations
  4. Server-Side Rendering: Can be extended to handle SSR scenarios where window is undefined
  5. Future-Proofing: Allows adding window-related logic without changing all usage sites

Notes

  • This hook is primarily used internally by other hooks in the library
  • In production code, you can often access window directly, but using this hook maintains consistency
  • For server-side rendering scenarios, this hook would need to be extended to handle cases where window is undefined
  • The hook is intentionally simple to minimize overhead

Build docs developers (and LLMs) love