Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Webcam in React Component in ComponentWillUnmount

Tags:

reactjs

I have a react component that starts a webcam when a component called VideoPage is mounted.

However, when I navigate to another page, the webcam is still running in the background. I know this because the webcam activity light is still activated on my laptop.

I believe I will to 'kill' the webcam in the React lifecycle method ComponentWillUnmount when the component unmounts. How can I achieve that?

My code is below. I appreciate the advice. Thanks!

import React from "react";

export default class VideoPage extends React.Component {
  constructor(props) {
    super(props);

    this.videoTag = React.createRef();

    this.state = {
      loading: false
    };
  }

  componentDidMount() {
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then(this.handleStream)
      .catch(err => console.log(err));
  }

  handleStream = async stream => {
    // start receiving stream from webcam
    this.videoTag.current.srcObject = stream;

    console.log("The video is ready");
  };

  render() {
    return (
      <div>
        <div style={{ paddingTop: 20 }}>
          <video
            id="myvideo"
            ref={this.videoTag}
            width={426}
            height={240}
            autoPlay
            title="video"
          />
        </div>
      </div>
    );
  }
}
like image 420
Hendry Lim Avatar asked Oct 26 '25 10:10

Hendry Lim


1 Answers

To stop a getUserMedia request, you need to call the stop() method of the MediaStreamTracks it generated.
To access these MediaStreamTracks, you need to call the getTracks() method of the stream MediaStream you received in your handleStream method.

So it would be good to save your stream somewhere in your instance, e.g as this.stream.
Then in your componentWillUnmount, you will call

this.stream.getTracks()
  .forEach((track) => track.stop());
like image 85
Kaiido Avatar answered Oct 29 '25 00:10

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!