Next.js Discord

Discord Forum

websockets issue

Answered
Whiteleg shrimp posted this in #help-forum
Open in Discord
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?
Answered by Ray
useEffect run twice in development with strict mode enabled
View full answer

7 Replies