KestVir
KestVir

Reputation: 350

Can't access updated state inside useEffect hook

I have a node server which listens for the load video event and then emits load event, to load a video.

I listen for this event inside my client-side like this:

useEffect(() => {
    socketRef.current = io.connect('/');

    socketRef.current.on("load", () => {
        loadVideo();
    })
}, []);

For this example, the loadVideo function just logs the value of videoID, which gets set like this:

<input type="text" placeholder="video link" value={videoID} onChange={e => setVideoID(e.target.value)} />

Every time when the loadVideo function gets executed from inside the useEffect, it logs the initial state, which is an empty string, but if I were to call the function from some other function which is not inside a useEffect, then it logs the updated value. Could anyone explain why that is?

Upvotes: 2

Views: 1094

Answers (1)

k-wasilewski
k-wasilewski

Reputation: 4623

It's because your useEffect has no dependencies, meaning it's called on component mounting only. I would add the videoId as its dependency.

And just a sidenote, if you posted your loadVideo code here, it wouldn't hurt :)

Upvotes: 2

Related Questions