How to consume server sent events in React

Let's learn how to consume a server sent events in React in this article, we will use the same example from the previous article.

import React, { useEffect, useState } from 'react'

const App = () => {
  const [score, setScore] = useState({})

  useEffect(() => {
    // Create a new EventSource
    const eventSource = new EventSource('http://localhost:3000/scores')

    // Listen to the message event
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data)
      setScore(data)
    }

    return () => {
      // close the server connection
      eventSource.close()
    }
  }, [])

  return (
    <div>
      <h2>Live Football Scores</h2>
      <p>Team: {score.team}</p>
      <p>Goals: {score.goals}</p>
      <p>Possession: {score.possession}</p>
    </div>
  )
}

Here we just created a new EventSource object and passed the URL of the server sent events endpoint. Then we listened to the message event and parsed the data. We also closed the connection when the component unmounts.

How event source works?

EventSource is a keep-alive connection between the client and the server. The server can send data to the client without the client requesting it. We will see about event source in other article.

Hope you learnt on how to consume server sent events in React. Thanks for reading, happy coding 🙏

If you want to learn how to send the data using SSE in node Js, You can check our previous article how to send server sent events in Node.js.

Beginners to ProNode Js

Visual Guide to API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

Visual Guide to API Design Best Practices