Re-Render Client Component When Parent Server Component Receives Data

I have a server component that passes a “messages” array to a client component via props.

The server component successfully listens for a “client.on(conversationUpdated)” and updates the messages array.

How do I get the client component to show the new array?

I assumed the props would be updated and I could just useEffect to set the new messages state but I don’t think the client component is receiving the props change after the parent server component changes the array. I’m not experienced enough to know if I should expect that behavior.

Any help would be greatly appreciated.

Hi, @pjgorton!

To update a client component when a server component’s data changes in Next.js, you can implement a real-time update mechanism using Server-Sent Events (SSE). Here’s a summary of the approach:

  1. Create an SSE endpoint using a Next.js Route Handler.
  2. In your client component, use the EventSource API to listen for updates from the SSE endpoint.
  3. When your server receives updates (e.g., from a “conversationUpdated” event), send them to the SSE endpoint.
  4. The client component will receive these updates and can update its state accordingly.

For example:

'use client'

import { useState, useEffect } from 'react'

export function Messages({ initialMessages }) {
  const [messages, setMessages] = useState(initialMessages)

  useEffect(() => {
    const eventSource = new EventSource('/api/sse')
    eventSource.onmessage = (event) => {
      const newMessage = JSON.parse(event.data)
      setMessages(prevMessages => [...prevMessages, newMessage])
    }
    return () => eventSource.close()
  }, [])

  return (
    <ul>
      {messages.map(message => (
        <li key={message.id}>{message.content}</li>
      ))}
    </ul>
  )
}

Let us know how you get on! You could also try sharing what you’ve done with v0.dev :smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.