websockets issue
Answered
Whiteleg shrimp posted this in #help-forum
Whiteleg shrimpOP
'use client';
import { createContext, useContext, useMemo, useEffect } from 'react';
import io from 'socket.io-client';
const WSStateContext = createContext(null);
export function WSProvider({ children }){
const wsInstance = useMemo(() => {
if (typeof window == 'undefined') return null;
const socket = io({
path: '/api/socket',
serveClient: false,
reconnection: true,
reconnectionAttempts: 3,
reconnectionDelay: 900,
reconnectionDelayMax: 3000,
randomizationFactor: 0.3,
});
return socket;
}, []);
useEffect(() => {
return () => {
wsInstance?.close();
};
}, []);
return <WSStateContext.Provider value={wsInstance}>{children}</WSStateContext.Provider>;
};
export function useWS(){
const context = useContext(WSStateContext);
return context;
};why does it run wsInstance?.close(); right when i load the page and how do i prevent it from connecting to the socket multiple times?
7 Replies
Whiteleg shrimpOP
what should i do then?
@Whiteleg shrimp what should i do then?
I think it is fine as long as you have clean it up
it will only run once in production
Whiteleg shrimpOP
ok
other option will be disable strict mode but I wouldn't recommend it since it help preventing some weird bug
Whiteleg shrimpOP
ðŸ‘