react js socket io code example
Example 1: import socket io frontend
<script src="/socket.io/socket.io.js"></script><script> const socket = io('http://localhost');</script>
Example 2: how react with socket
connect to the socket server on component mount with useEffect
save each new incoming message in the component's state.
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("FromAPI", data => {
setResponse(data);
});
}, []);
return (
<p>
It's <time dateTime={response}>{response}</time>
</p>
);
}
Example 3: socket io react js
npm install socket.io