signalr
  1. signalr-signalrwith-react

SignalR with React

Syntax

import * as signalR from "@microsoft/signalr";

const connection = new signalR.HubConnectionBuilder()
        .withUrl('/myhub')
        .build();

connection.start()
         .then(() => {
            console.log('Connection started');
          })
          .catch(err => console.error(err));

connection.on('ReceiveMessage', message => {
           console.log(message);
        });

Example

import { useEffect, useState } from 'react';
import * as signalR from "@microsoft/signalr";

function App() {
  const [connection, setConnection] = useState(null);
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    // create connection
    let newConnection = new signalR.HubConnectionBuilder()
      .withUrl("https://localhost:44324/myHub")
      .withAutomaticReconnect()
      .build();
    setConnection(newConnection);
  }, []);

  useEffect(() => {
    if (connection) {
      // start connection
      connection.start()
        .then(() => {
          console.log('Connection started');
        })
        .catch(err => console.error(err));

      // listen for incoming messages
      connection.on('ReceiveMessage', message => {
        setMessages(prevMessages => [...prevMessages, message]);
      });
    }
  }, [connection]);

  const sendMessage = async () => {
    try {
      // send message to server
      await connection.invoke('SendMessage', 'User1', 'Hello from React');
    } catch (e) {
      console.error(e);
    }
  };

  return (
    <div>
      <ul>
        {messages.map((msg, idx) => (
          <li key={idx}>{msg}</li>
        ))}
      </ul>
      <button onClick={sendMessage}>Send Message</button>
    </div>
  );
}

export default App;

Output

The output will show on the console log by adding some features.

Explanation

SignalR is a library for real-time web applications, which allows server-side code to push content to clients instantly. SignalR with React provides high performance and user experience. In this example, we have created a HubConnection that connects to the SignalR server and listens for incoming messages. When a message is received, it is added to the messages state.

The sendMessage function sends a message to the SignalR server using the invoke method. This method takes two arguments - the name of the server-side method to call, and the parameters to pass to that method.

Use

SignalR with React can be used for real-time web applications that require high-performance and user experience. It can be used for chat applications, stock market tickers, gaming, and many other applications where real-time updates are required.

Important Points

  • Ensure that the SignalR server is configured correctly and is accessible from the client.
  • The HubConnection should be initialized only once per component.
  • Use useEffect to start or stop the connection and listen for incoming messages.
  • Use invoke to call server-side methods.

Summary

SignalR with React provides a powerful solution for building real-time web applications that require high performance and user experience. It allows server-side code to push content to clients instantly, making it ideal for chat applications, stock market tickers, gaming, and many other applications where real-time updates are required. With the help of SignalR, developers can easily build scalable and high-performing web applications.

Published on: