Hi I am trying to implement live streaming video in my website, For that i have used node media server, The problem i am facing here is my website get caught into infinite re-rendering because of function in which I have created a player. Is there any solution for this specially in react hooks. I am sharing a piece of code sufficient to understand the problem.
const videoRef = useRef();
const {id } = props.match.params;
useEffect(() => {
props.fetchStream(id);
buildPlay();
}, [buildPlay]);
function buildPlay() {
if(player || !props.stream){
return ;
}
var player = flv.createPlayer({
type: 'flv',
url: `http://localhost:8000/live/${id}.flv`
});
player.attachMediaElement(videoRef.current);
player.load();
}
if(!props.stream){
return <div>Loading...</div>
}
return (
<div>
<video ref={videoRef} style={{width: "100%"}} controls/>
<h1>{props.stream.title}</h1>
<h5>{props.stream.description}</h5>
</div>
)
What is causing infinite re-renders is that everything declared in a component function body is re-declared on every render, so
buildPlayis a new function every render, and the effect will execute infinitely. It's not really common to specify a function as a dependency (except aprops.callbackmaybe), but if you really want it, you should move the function out of the component and parameterize it (see show code snippet & run below).Looking at
buildPlay, what actually changes and should be specified as dependencies in this case is[props.match.params.id, props.stream, videoRef.current]. Your effect code should look like:Have a look at the 2 React apps in the snippet below: the first one takes your approach, the second one moves the dependeny function outside the component and parameterizes it.