MediaAdvancedSSR-safehooks/media/useMediaDevices.ts

useMediaDevices

Enumerate cameras/mics.

Import

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

API

Signature

useMediaDevices() → { devices, loading, supported, refresh }

When to use

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

SSR / Next.js

Client-only browser APIs.

Live playground

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

Live playgroundEdit · run with real @/hooks · useMediaDevices
Editor
function Devices() {
  const { devices, loading, supported } = useMediaDevices();
  if (!supported) return <p>Not supported</p>;
  if (loading) return <p>…</p>;
  return <ul>{devices.map((d) => <li key={d.deviceId}>{d.label || d.kind}</li>)}</ul>;
}
Preview

Implementation source

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

hooks/media/useMediaDevices.ts
import { useCallback, useEffect, useState } from 'react';
import { hasNavigator, isBrowser } from '../utility/isBrowser';

export interface UseMediaDevicesReturn {
  devices: MediaDeviceInfo[];
  loading: boolean;
  error: Error | null;
  supported: boolean;
  refresh: () => Promise<void>;
}

/** Enumerates media devices when supported. */
export function useMediaDevices(): UseMediaDevicesReturn {
  const supported =
    isBrowser() &&
    hasNavigator() &&
    !!navigator.mediaDevices?.enumerateDevices;

  const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const refresh = useCallback(async () => {
    if (!supported) {
      setError(new Error('Media devices API is not supported'));
      return;
    }
    setLoading(true);
    try {
      const list = await navigator.mediaDevices.enumerateDevices();
      setDevices(list);
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e : new Error(String(e)));
    } finally {
      setLoading(false);
    }
  }, [supported]);

  useEffect(() => {
    if (!supported) return;
    void refresh();
    const handler = () => {
      void refresh();
    };
    navigator.mediaDevices.addEventListener?.('devicechange', handler);
    return () => {
      navigator.mediaDevices.removeEventListener?.('devicechange', handler);
    };
  }, [supported, refresh]);

  return { devices, loading, error, supported, refresh };
}

Copy-paste example

useMediaDevices.example.tsx
'use client';

import { useMediaDevices } from '@/hooks';

export function Devices() {
  const { devices, loading, supported } = useMediaDevices();
  if (!supported) return <p>Not supported</p>;
  if (loading) return <p>…</p>;
  return <ul>{devices.map((d) => <li key={d.deviceId}>{d.label || d.kind}</li>)}</ul>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Always stop tracks on unmount (hooks clean up streams they own).
  • Source of truth: open hooks/media/useMediaDevices.ts for implementation details