Enable Dark Mode!
how-to-do-polling-in-react-short-polling-and-long-polling.jpg
By: Alan Joy

How to Do Polling in React (Short Polling & Long Polling)

Technical React

Keeping data fresh is one of those problems every web app eventually runs into — whether you're building a notification system, a live dashboard, a chat feature, or a monitoring tool.

WebSockets get a lot of attention, but polling remains a go-to for many teams. It's straightforward, works everywhere, and doesn't require much infrastructure to get right.

What is Polling?

Polling is a method where the client repeatedly sends requests to the server to check for new data.

Think of it like asking someone the same question again and again: “Any new updates?

Polling is commonly used when:

  • You need near real-time updates
  • WebSockets feel unnecessary or too complex
  • You want a simpler backend setup

Types of Polling

There are two main types:

  • Short Polling: The client sends requests at fixed intervals.
  • Long Polling: Client waits until the server responds with new data

1. Short Polling in React

Short polling means the client sends requests at regular times like every 5 seconds.

Example Use Cases

  • Dashboard metrics
  • Task progress updates
  • Notification counters

Basic Implementation

We can use short polling in React by using the setInterval function inside the useEffect function.

import { useEffect, useState } from "react";
export default function Notifications() {
  const [notifications, setNotifications] = useState([]);
  const fetchNotifications = async () => {
    try {
      const response = await fetch("/api/notifications");
      const data = await response.json();
      setNotifications(data);
    } catch (error) {
      console.error("Error fetching notifications:", error);
    }
  };
  useEffect(() => {
    fetchNotifications();
    const interval = setInterval(fetchNotifications, 5000);
    return () => clearInterval(interval);
  }, []);
  return (
    <div>
      <h2>Notifications</h2>
      {notifications.map((item) => (
        <p key={item.id}>{item.message}</p>
      ))}
    </div>
  );
}

How it works

  • fetchNotifications() fetches data from the server.
  • setInterval() calls it every 5 seconds.
  • Cleanup function clears the interval when the component unmounts.

2. Long Polling in React

Long polling is more efficient than short polling. Of sending requests every few seconds the client:

  • Sends a request
  • The server keeps the request open
  • When new data is available, the server responds
  • The client immediately sends another request

Basic implementation

import { useEffect, useState } from "react";
export default function Messages() {
  const [messages, setMessages] = useState([]);
  const startLongPolling = async () => {
    try {
      const response = await fetch("/api/messages/subscribe");
      const data = await response.json();
      setMessages((prev) => [...prev, data]);
      startLongPolling();
    } catch (error) {
      console.error("Polling error:", error);
      setTimeout(startLongPolling, 3000);
    }
  };
  useEffect(() => {
    startLongPolling();
  }, []);
  return (
    <div>
      <h2>Messages</h2>
      {messages.map((msg, index) => (
        <p key={index}>{msg.text}</p>
      ))}
    </div>
  );
}

How this works

  • fetchNotifications() gets data from the server.
  • setInterval() runs it every 5 seconds.
  • The cleanup function clears the interval when the component unmounts.

Polling is one of the simplest ways to keep your React app in sync with the server. With short polling, you hit the server on a fixed interval — every few seconds, regardless of whether anything changed. Long polling takes a different approach: the server holds the request open until there's actually something new to send back. Both have their place, and you'll find them in everything from dashboards and monitoring tools to notification feeds.

To read more about What are the Key Features in React 19, refer to our blog What are the Key Features in React 19.


Frequently Asked Questions

What is the difference between short polling and long polling?

Short polling is when you send requests at fixed intervals, like every few seconds. Long polling is when you keep the request open until the server has new data, making it more efficient.

Is polling better than WebSockets?

Polling is easy to set up and understand. But, if you need something to happen in real time like a live update, WebSockets are the way to go.

How often should I use short polling?

It depends on your use case, but a common interval is 3–10 seconds to balance performance and server load.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, KINFRA Techno Park
Kakkanchery, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message