'why is Socket.io not working on client side?

I want to use socket.io-client on vanilla react without context. This socket.on listener on third useEffect does not work if I don't re-render this page, where I have done setSocket(HomeScreen.jsx), the event no longer fires and I get Cannot read properties of null (reading 'emit'). So, if I want it to work, then I have to make this page re-render for the event to work after every successful event firing. I am pretty sure this is a frontend mistake since I am console.logging all the socket.ids to emit successfully on the backend.

I would also like to know on how I can separate the third useEffect to a different component or have socket.io listeners on different component where I did not set the socket. Is it possible through passing components? If so, how?

I am new to socket.io-client and I want to use vanilla react without context. I thinik I am facing these issues due to not having proper structure on socket.io-client

This code for socket.io occurs after successful log in where I set the localStorage authToken and get to HomeScreen.jsx. Please help me out to better re-structure my socket.io code on the client side.

HomeScreen.jsx:

useEffect(() => {
        if(localStorage.getItem('authToken') && !localStorage.getItem('showedLoginStatus')){
            toast.success("Login successful!");
            localStorage.setItem('showedLoginStatus', 'showed');
        }
        setSocket(io.connect(backendLink));
    }, [])

    useEffect(() => {
        console.log(socket, localStorage.getItem('authToken'));
        socket?.emit("newUser", localStorage.getItem('authToken'));
    }, [socket])

    useEffect(() => {
        socket?.on("notifyFriendRequest", () => {
            console.log('sent');
            // readRequests();
        })

        return () => socket?.off("notifyFriendRequest");
    }, [socket])


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source