Wednesday, November 26, 2025

thumbnail

How to Implement Real-Time Features with SignalR and React

 How to Implement Real-Time Features with SignalR and React


SignalR is a library from Microsoft that enables real-time communication between servers and clients. It is commonly used for:


Live chat apps


Activity dashboards


Real-time notifications


Live data updates (prices, metrics, IoT)


Collaborative apps (whiteboards, editors)


Below is a simple step-by-step process to implement SignalR with a React frontend and a .NET backend.


1. Set Up the Backend (ASP.NET Core)


First, install the SignalR server package:


dotnet add package Microsoft.AspNetCore.SignalR


Create the Hub Class


A Hub is a server-side class that manages connections and messaging.


using Microsoft.AspNetCore.SignalR;


public class ChatHub : Hub

{

    public async Task SendMessage(string user, string message)

    {

        await Clients.All.SendAsync("ReceiveMessage", user, message);

    }

}


Register SignalR in Program.cs

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddSignalR();


var app = builder.Build();


app.MapHub<ChatHub>("/chatHub");


app.Run();



This exposes a SignalR endpoint at:


/chatHub


2. Install SignalR Client in React


Inside your React project:


npm install @microsoft/signalr


3. Create the SignalR Connection in React


Below is the simplest version of connecting React to SignalR.


import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";

import { useEffect, useState } from "react";


function App() {

  const [connection, setConnection] = useState(null);

  const [messages, setMessages] = useState([]);


  useEffect(() => {

    const connect = new HubConnectionBuilder()

      .withUrl("https://localhost:5001/chatHub")

      .configureLogging(LogLevel.Information)

      .withAutomaticReconnect()

      .build();


    connect.start()

      .then(() => {

        console.log("Connected!");


        connect.on("ReceiveMessage", (user, message) => {

          setMessages(prev => [...prev, { user, message }]);

        });

      })

      .catch(err => console.log("Connection failed:", err));


    setConnection(connect);

  }, []);


  return (

    <div>

      <h2>Messages</h2>

      {messages.map((m, index) => (

        <div key={index}>

          <strong>{m.user}: </strong>{m.message}

        </div>

      ))}

    </div>

  );

}


export default App;


4. Sending Messages from React


Add input fields to send messages.


const sendMessage = async () => {

  if (connection) {

    try {

      await connection.invoke("SendMessage", user, message);

      setMessage("");

    } catch (e) {

      console.log(e);

    }

  }

};



Add a simple UI:


<input

  value={user}

  onChange={(e) => setUser(e.target.value)}

  placeholder="User"

/>

<input

  value={message}

  onChange={(e) => setMessage(e.target.value)}

  placeholder="Message"

/>

<button onClick={sendMessage}>Send</button>


5. Enabling Automatic Reconnect


SignalR supports automatic reconnection:


.withAutomaticReconnect()



This helps in real-world remote environments where connection drops happen.


6. Security & Authentication (Optional)


If your app needs secure real-time features:


Use JWT tokens


Protect your hub using .RequireAuthorization()


Pass access token in .withUrl()


Example:


.withUrl("/chatHub", { accessTokenFactory: () => token })


7. Common Real-Time Features You Can Build

1. Live Chat


Messages appear instantly using SendAsync and ReceiveMessage.


2. Real-Time Notifications


Server pushes alerts (e.g., new order, status change).


3. Live Dashboards


Stream live data updates → charts update immediately.


4. Collaborative Apps


Cursor positions, typing indicators, shared documents.


5. Admin Panels


Live user activity, logs, monitoring dashboards.


8. Tips for Production-Ready SignalR Apps


Use Azure SignalR Service for scaling


Use Redis backplane when running multiple servers


Handle reconnection events in UI


Avoid broadcasting too frequently (use throttling)


Use logs to debug connection issues


Summary


Implementing real-time features with SignalR and React involves:


Creating a SignalR Hub in ASP.NET Core


Setting up connection and handlers in React


Using .invoke() to send data to the server


Using .on() to receive data from the server


Adding reliability with automatic reconnect


Using authentication and scaling options for production


With these steps, you can build anything from a simple chat app to a complex real-time enterprise dashboard.

Learn Dot Net Course in Hyderabad

Read More

Building Mobile Apps with Blazor WebAssembly

How to Use Webpack for Full Stack .NET Front-End Projects

Working with TypeScript and JavaScript in Full Stack .NET

Front-End Technologies & Frameworks

Visit Our Quality Thought Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive