1

In video.js's official document https://docs.videojs.com/tutorial-react.html

we have

  componentDidMount() {
    // instantiate Video.js
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
      console.log('onPlayerReady', this)
    });
  }

I want to create functional component with hooks

export default function VideoPlayer(props) {
  const player = useRef(null);
  const videoNode = useRef(null);
  useEffect(() => {
    player.current = videojs(videoNode.current, props);

    return () => {
      if (player.current) {
        player.current.dispose()
      }
    }
  }, []);//I have problem with dependency array
  return (
    <div data-vjs-player>
      <video ref={videoNode} className="video-js"/>
    </div>
  )
}

I have warning

ESLint: React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array.(react-hooks/exhaustive-deps)

If I change dependency array from [] to [props] useEffect runs on each render , I just want run it on first time , like componentDidMount

How can I exactly create componentDidMount using hooks?

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
WebMaster
  • 3,050
  • 4
  • 25
  • 77

1 Answers1

1

As explained here, you used useEffect as intended. An empty dependency array means that it will run only once (as componentDidMount). The error pointed out informs you if you actually had other intentions, the effect won't render again.

To dismiss the error, you can simply paste the following comment // eslint-disable-line react-hooks/exhaustive-deps at the end of useEffect

useEffect(() => {
  player.current = videojs(videoNode.current, props);

  return () => {
    if (player.current) {
      player.current.dispose()
    }
  }
}, []); // eslint-disable-line react-hooks/exhaustive-deps

REFERENCE

This answer explains it more thoroughly

David Buzatu
  • 624
  • 8
  • 18