-2

I am working on a React project and in there I have to initialize a socket once the component's been mounted. For that I am using this syntax and I want to know whether or not it is valid.

function Component() {
    const socket = useMemo(() => {
        return io('http://localhost:3001')
    },[socket]);

    return (
        <h1>Component</h1>
    )
}

This way, my project and the sockets are working just fine but I want to know the conventional way to achieve the same. I used the same syntax in another React project and it gave me a "Reference Error" for the socket variable.

4

1 回答 1

1

You need to add a dependency array to your useMemo, otherwise it'll be triggered at each render. After that, yes it's a valid syntax :)

const socket = useMemo(() => {
    return io('http://localhost:3001')
}, [])
于 2022-02-17T08:11:00.450 回答