Skip to content Skip to sidebar Skip to footer

Correct Handling Of React Hooks For Streaming Video Camera To Html Video Element

I've been trying to write a React Hook for handling steaming video captured from a users camera to an HTML Video Element. I'm having trouble working out the best way to handle init

Solution 1:

If you add a cleanup function within any of the useEffect which has parameters specified as a dependency array, the cleanup function will be run whenever any of the parameters change.

In order for the video cleanup to only run on unmount, you would have to pass an empty dependency array. Now since the variables inside the effect will belong to the closure at the initial run, you would need to have a ref that references those values.

You can write a cleanup hook to take care of that

constuseCleanup = (val) => {
    const valRef = useRef(val);
    useEffect(() => {
       valRef.current = val;
    }, [val])

    useEffect(() => {
        return() => {
              // cleanup based on valRef.current
        }
    }, [])
}



import { useEffect, useState } from'react';

const initialiseCamera = async() => await
    navigator
        .mediaDevices
        .getUserMedia({audio: false, video: true});

exportconstuseCamera = videoRef => {
    const [isCameraInitialised, setIsCameraInitialised] = useState(false);
    const [video, setVideo] = useState(null);
    const [error, setError] = useState('');
    const [playing, setPlaying] = useState(true);

    useEffect(() => {
        if(video || !videoRef.current) {
            return;
        }

        const videoElement = videoRef.current;
        if(videoElement instanceofHTMLVideoElement) {
            setVideo(videoRef.current);
        }
    }, [videoRef, video]);


    useCleanup(video)

    useEffect(() => {
        if(!video || isCameraInitialised || !playing) {
            return;
        }

        initialiseCamera()
            .then(stream => {
                video.srcObject = stream;
                setIsCameraInitialised(true);
            })
            .catch(e => {
                setError(e.message);
                setPlaying(false);
            });
    }, [video, isCameraInitialised, playing]);

    useEffect(() => {
        const videoElement = videoRef.current;

        if(playing) {
            videoElement.play();
        } else {
            videoElement.pause();
        }

    },[playing, videoRef]);



    return [video, isCameraInitialised, playing, setPlaying, error];
};

Post a Comment for "Correct Handling Of React Hooks For Streaming Video Camera To Html Video Element"