one-hook
Size
0.57 kb
View source

useUserMedia

Access and manage media devices like camera and microphone.

Installation

npm install @1hook/use-user-media

Usage

import {  } from '@1hook/use-user-media'

Pass the media constraints to the hook.

const { , , , ,  } = ({
  : true,
})

The hook follows a simple state machine:

  • Initially starts in "closed" state with stream: null
  • Calling open() transitions to "loading" state while requesting device access
  • On successful device access, transitions to "open" state with stream: MediaStream
  • If an error occurs during loading, transitions to "error" state with the error details
  • Calling close() returns to "closed" state, stops the stream, and sets stream: null

This predictable state flow makes it easy to build UIs that respond appropriately to the media stream's status.

Example

Capture and display video from the device's camera.

import { ,  } from 'react'
import {  } from '@1hook/use-user-media'

export default function () {
  const { , , ,  } = ({
    : true,
  })

  const  = <HTMLVideoElement | null>(null)

  // use the stream to reproduce the video
  (() => {
    if (!.) return
    .. = 
  }, [])

  return (
    <>
      < ={}  />

      < ={ === 'closed' ?  : }>
        { === 'closed' ? 'Open' : 'Close'} Camera
      </>
    </>
  )
}

Parameters

UseUserMediaOptions

The options of the useUserMedia hook. See MDN docs  for more details.

PropTypeDefault
video?
boolean | MediaTrackConstraints
-
preferCurrentTab?
boolean
-
peerIdentity?
string
-
audio?
boolean | MediaTrackConstraints
-

UseUserMediaReturn

The return value of the useUserMedia hook.

PropTypeDefault
toggleVideo
() => void
-
toggleAudio
() => void
-
close
() => void
-
open
() => void
-
videoState
"none" | "enabled" | "disabled"
-
audioState
"none" | "enabled" | "disabled"
-
error
Error | null
-
state
"closed" | "error" | "open" | "loading"
-
stream
MediaStream | null
-

On this page