Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Socket.io resets my pre-defined state variables when listening to a message

I have seen similar questions, but none have fixed my problem unfortunately.

I have a component which saves some states on mount, using useEffect:

useEffect(() => {
    const openWebPianoUtil = new OpenWebPiano();
    openWebPianoUtil.init(new AudioContext())
    setOpenWebPianoInstance(openWebPianoUtil);

    return () => socket.disconnect();
}, []);

Considering that setOpenWebPianoInstance is a state setter function.

I have another useEffect hook in that component that will trigger by the openWebPianoInstance state, and will listen to the socket messages:

 useEffect(() => {
    console.log(openWebPianoInstance);
    socket.on("noteOn", (note) => {
        console.log(openWebPianoInstance);
        console.log('got a note from socket: ', note);
        onNoteChange(note, true);
    });
}, [openWebPianoInstance])

While the first console.log(openWebPianoInstance) in the useEffect will show the updated data of openWebPianoInstance, in the socket.on callback, the openWebPianoInstance state is suddenly null again (which is its initial state).

I tried putting the socket code in the first useEffect hook which listens to the component mount, but it also did the same thing.

Why is the state reset every time the socket message is received? Does it do something behind the scenes that i'm missing?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!