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.

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months