Skip to content

useMediaDevices

This hook uses the user media devices (camera and microphone) and returns their states and controls as well as their stream object.

Options

NameTypeDescription
refRefObjecta <video> element reference.
startOnMountBooleanstart automatically when the component is mounted (default is false).

Return Values

NameTypeDescription
refRefObjecta <video> element reference.
streamRefObjectthe MediaStream object reference that you can use with a video element as srcObject, or with an AudioContext.
devicesArrayan array of the user's media devices.
startFunctiona function to start streaming, and it can take the user media constraints as a parameter (default is the initial constraints).
stopFunctiona function to stop streaming.

Example Usage

tsx
import { useMediaDevices } from 'react-pre-hooks';

export default function Example() {
  const { ref, start, stop } = useMediaDevices({ video: true, audio: true });

  return (
    <main>
      <video ref={ref} />
      <button onClick={() => start()}>Start</button>
      <button onClick={() => stop()}>Stop</button>
    </main>
  );
}
import { useMediaDevices } from 'react-pre-hooks';

export default function Example() {
  const { ref, start, stop } = useMediaDevices({ video: true, audio: true });

  return (
    <main>
      <video ref={ref} />
      <button onClick={() => start()}>Start</button>
      <button onClick={() => stop()}>Stop</button>
    </main>
  );
}

Released under the MIT License.