'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?
#websockets issue
9 messages · Page 1 of 1 (latest)
🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord
🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize
✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)
useEffect run twice in development with strict mode enabled
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
ok
other option will be disable strict mode but I wouldn't recommend it since it help preventing some weird bug
👍