Skip to content

Bug: WebSocket doesn't connect when called inside useEffect #33677

Closed
@eric369java

Description

@eric369java

Hi, I'm trying to connect to a websocket to my fastapi backend from inside useEffect() inside of a custom hook. I.e. inside of useCustom.ts, I have something like:

export default function useCustom(url) {

    useEffect(() => {
        const ws = new WebSocket(url)
        ws.onopen = () => {console.log('opened')}
    }, [])
}

The message "opened" is never printed when running this. However, if I move the websocket code outside of useEffect, everything runs & prints as I expect.

export default function useCustom(url) {
       const ws = new WebSocket(url)
       ws.onopen = () => {console.log('opened')}
}

I've also tried saving the websocket as a ref, or adding / removing the return cleanup function in useEffect to no avail. I am running both my frontend and backend on localhost. The url is something like ws://0.0.0.0:8000/ws/endpoint. If I try connecting my frontend to a remote server like wss://ws.ifelse.io it works both inside and outside of useEffect.

To reproduce, just make a simple fastapi backend like

from fastapi import FastAPI, WebSocket

app = FastAPI()

# socket at ws://0.0.0.0:8000/ws
@app.websocket("/ws")
async def test_socket(websocket : WebSocket):
    await websocket.accept()
    while True:
           text = await websocket.receieve_text()
           print(text)

Is there any reason why using web socket from inside useEffect behaves differently than when used outside ? Thanks.

React version: 19

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions