I'm using websockets in my React application. The application is supposed to consist of function components only.
Imagine the application consists of two "tabs": one irrelevant, and the other one, a chat using websockets. Given that, we want to whip up a websocket connection once the user enters the chat tab.
How should the component handle the websocket object? Since we want to clean up once the user switches back to the other tab (WebSocket.close()), it sounds like we should be using an effect hook here.
const Chat = () => {
const [messages, setMessages] = useState([]);
useEffect(() => {
const webSocket = new WebSocket("ws://url");
webSocket.onmessage = (message) => {
setMessages(prev => [...prev, message.data]);
};
return () => webSocket.close();
}, []);
return <p>{messages.join(" ")}</p>;
};
Works! But now, imagine we want to reference the webSocket variable somewhere outside the useEffect scope - say, we want to send something to the server once the user clicks a button.
Now, how should it be implemented? My current idea (albeit a flawed one, I feel) is:
const Chat = () => {
const [messages, setMessages] = useState([]);
const [webSocket] = useState(new WebSocket("ws://url"));
useEffect(() => {
webSocket.onmessage = (message) => {
setMessages(prev => [...prev, message.data]);
};
return () => webSocket.close();
}, []);
return <p>{messages.join(" ")}</p>;
};
Kinda works, nevertheless I feel like there's a better solution.