React State Resets to Default When WebSocket Message is Received

I’m working on a React project where I’m using WebSockets to receive real-time updates. However, I’m encountering an issue where my component’s state resets to the default value every time a WebSocket message is received. I’ve been trying to debug this, but haven’t been able to figure out why this is happening. Thank you for your help in advance :).

useEffect(()=>{
   const connect = ()=>{
       //code for connectiong to websocket
       ws = new websocket....

       ws.onmessage() = (message)=>{
         //here state is always initial 
         //state change code

         //after state change code it changes but when new message arrives its in the initial state 
        }
   }
},)

Initially I was using useState hook after that I used useReducers in both the case it happens.