Introduction
Building real-time applications is one of the most interesting but intimidating parts of modern web development.Whether it is a chat application, a dashboard for showing live stock updates, online gaming, or as basic as a real-time notification system.Users want data to change in real-time without page reloading. Two of the most distinguishing methods in React for meeting such real-time requirements take the center stage: Polling and WebSockets.
On a high level, both methods achieve the same thing synchronizing the client interface with the server. However, they achieve it, and the compromises they entail, are quite distinct.Polling is the traditional method, where the client repeatedly “asks” the server if there’s new data, usually at fixed intervals. WebSockets, on the other hand, offer a more modern and efficient solution by maintaining a persistent connection between client and server, enabling instant bi-directional communication.
So, when would you want to use each in your React app? It depends on whether real-time is absolutely indispensable, how complex your backend is going to be, and the greatest number of users that your app needs to handle at a time. Let’s dissect both strategies in the current blog, implement them step-by-step in React, and then compare.
What is Polling?
Polling is a technique where your app repeatedly asks the server for new information at fixed
time intervals (like every 5 seconds). If there’s new data, the server sends it back; if not, the server still responds saying there’s nothing new.
It is simple to use and backend-agnostic, but it is not very efficient since a majority of the requests do not include new information.You’ll also find that your server is being bombarded with repeated requests, even when no alteration whatsoever is detected. That is among the significant negatives of polling.
Backend Setup (Polling with JSON Server)
We need to set up a backend that can provide data. We’ll use json-server. It provide a mock REST API that behaves like a real server.
First of all install json-server on your system :
npm install -g json-server
- Creating a Mock Database
Create a db.json file in the root directory of your project. It will act as our database. This file will act as our database. Add the following content :
{
“messages”: [
{ “id”: 1 , “text”: “Hello from server” },
{ “id”: 2 , “text”: “New update available” },
{ “id”: 3 , “text”: “Polling work fine” }
]
}
- Running the Mock Server
Now,use below command to start your mock API server:
json-server --watch db.json --port 4000
This command tell json-server to “watch” the db.json file. It serve content as REST API on port 4000. Once server is started,you can visit this endpoint in your browser :
http://localhost:4000/messages
Sample response :
[
{ “id”: 1 , “text”:“Hello from server”},
{ “id”: 2 , “text”:“New update available”},
{ “id”: 3 , “text”:“Polling work fine”}
]
Now that our backends are ready, let’s build the React components.
Implementing Polling in React
Create a new file called PollingExample.tsx inside your src folder and put the below code into that file. After putting the code you can import <PollingExample /> into your main App.tsx to test how polling fetches data at regular intervals.
import React, { useState, useEffect } from “react”;
function PollingExample() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
// Function to fetch data from server
const fetchData = async () => {
try {
const response = await fetch(“http://localhost:4000/messages”);
const result = await response.json();
setData(result);
setLoading(false);
} catch (error) {
console.error(“Error while polling:” , error);
}
};
useEffect(() => {
fetchData();
const interval = setInterval(fetchData, 5000);
return () => clearInterval(interval);
}, []);
return (
Polling Example Output
{loading ? (
Loading...
) : (
{data.map((item, index) => (
- {item.text}
))}
)}
);
}
export default PollingExample;
After writing the above code, you see the output below on your screen.
What are WebSockets?
WebSockets is a communication protocol that provides continuous and bidirectional connection between the server and the client ( React app). Once connection is established , the server and the client are able to pass messages whenever they want without reconnecting. That is why the connection is suitable for real-time communication like chat, streaming dashboards, game playing, or live notification.
You can include the browser’s very own WebSocket API or Socket.IO for streamlined implementation and additional features with React. In prod deployments, you will need to utilize the secure version of the connection over the WebSocket, wss:// instead of ws:// so all the communications are encrypted and secured on the way.
Backend Setup (WebSockets with ws)
For our WebSocket example, we’ll create a lightweight backend using the ws library in Node.js. Unlike polling, WebSockets allow the server to push updates to the client in real time.
Start by installing the ws package, which provides WebSocket support for Node.js :
npm install ws
- Creating the WebSocket Server
Now, create a new file named server.js in your project root and add the following code :
const WebSocket = require(“ws”);
// Create a new WebSocket server on port 4000
const wss = new WebSocket.Server({ port: 4000 });
wss.on(“connection” , (ws) => {
console.log(“Client connected”);
// Send an initial real-time message
ws.send(JSON.stringify({ message: “this is real time”}));
// After a short delay, send another update
setTimeout(() => {
ws.send(JSON.stringify({ message: “another instance updated”}));
}, 3000);
// Handle messages coming from the client
ws.on(“message”, (msg) => {
console.log(“Received from client:” , msg);
ws.send(JSON.stringify({ message: `Echo: ${msg}`}));
});
// Handle client disconnect
ws.on(“close”, () => {
console.log(“Client disconnected”);
});
});
console.log(“WebSocket server is running on ws://localhost:4000”);
Start the WebSocket server by running below command :
node server.js
Your WebSocket server is now running on :
ws://localhost:4000
Now that our backends are ready, let’s build the React components.
Implementing WebSockets in React
Create a new file named WebSocketExample.tsx inside your src folder (e.g., src/WebSocketExample.jsx). Add the following code inside it. Then, you can import and use <WebSocketExample /> in your main App.tsx file to see it in action.
import React, { useState, useEffect } from “react”;
const WebSocketExample = () => {
const [messages, setMessages] = useState([ ]);
useEffect(() => {
const socket = new WebSocket(“ws://localhost:4000”);
socket.onopen = () => {
console.log(“Connected to WebSocket server”);
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((prev) => [...prev, data.message]);
};
socket.onerror = (error) => {
console.error(“WebSocket error:” , error);
};
socket.onclose = () => {
console.log(“WebSocket connection closed”);
};
return () => socket.close();
}, []);
return (
WebSocket Example Output
{messages.map((msg, i) => (
- {msg}
))}
);
};
export default WebSocketExample;
After writing the above code, you see the output below on your screen.
Polling vs WebSockets
Polling and WebSockets are two different ways to keep your React app updated with new data. Let’s see the key differences between Polling and WebSockets.
Feature | Polling | WebSockets |
How it works | Client sends requests to the server at fixed intervals (e.g., every 5 sec). | Client and server keep a single open connection and exchange data anytime. |
Connection type | Short-lived, new HTTP request each time. | Persistent, full-duplex connection. |
Data updates | Arrive only when the next request is made. | Delivered instantly as soon as they’re available. |
Efficiency | Many requests may return no new data, wasting resources. | Efficient data sent only when needed. |
Implementation | Simple, works with any backend via REST APIs. | Requires WebSocket support on server. |
Best suited for | Occasional or less time-sensitive updates (weather, dashboards). | Real-time apps like chat, gaming, notifications, live feeds. |
Conclusion
Both Polling and WebSockets are powerful ways of keeping your React applications up to date with new information, but they serve different needs. Polling is the old school and most basic solution, reliant on regular HTTP requests with fixed time gaps. It is simple to implement, requires no special server configuration, and is dependable for cases where updates happen not often or are time-insensitive. It is, though, inefficient as the majority of the calls come back with no new data.
WebSockets, in contrast, bring real-time to your app for real. Since they maintain a persistent, two-way connection open between client and server, data is pushed directly as it happens. That’s why they’re the default choice for chat apps, online multiplayer games, financial dashboards, or anywhere time and efficiency count most.
When you’ve got to pick between the two, ask your use case. If your application is updating intermittently and you care more about simplicity than you care about real-time responsiveness, then polling is typically “good enough”. If you care more about real-time responsiveness, then WebSockets will produce a much better user experience.

