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?