I'm building a chat app. Currently, my client component makes requests to a route handler inside useEffect to refresh the messages board twice every second or so. See example:
"use client";
import { useEffect, useState } from "react";
import message from "./messageType";
export default function MessagesWindow() {
const [messagesList, setMessagesList] = useState<message[]>([]);
useEffect(() => {
// Refresh messages refreshRate times per second.
const id = setInterval(() => {
fetch(/* Fetch from API endpoint */)
}, 500);
return () => clearInterval(id);
}, [messagesList]);
return (
<ul>
{messagesList.map((element: message) => {
return <li key={element._id}>{element.messageContent}</li>
});}
</ul>
);
}
This approach definitely works, but I've been advised I should be using a server component, to prevent overhead and remove the need for a separate route handler. I also hear that it reduces the Javascript sent to the client. However, if all the re-rendering is done on the server, it seems that the whole page would have to be downloaded. This makes sense if the request is occasional, but I'm not sure if it's the best approach here. However, the current use of useEffect
does seem somewhat hacky, so I'm wondering which approach would be the most optimized.
What you're looking for is dynamic rendering, which falls under server-side rendering strats when using Next.js.
Though a more full approach would be to leverage...