Getting infinite API requests when passing data as props from server side component to client component

12 hours ago 1
ARTICLE AD BOX
Server Component export default async function FriendsList() { const friendsList = await axios.get( "http://localhost:8000/api/chat/get-friends", { withCredentials: true } ) return ( <> <ChatSidebar friends={friendsList.data.friendsList} /> </> ) } client component "use client" export default function TerminalSidebar( { friends }: { friends: { name: string }[] } ) { const [userFriends, setUserFriends] = useState(friends) return ( <> {userFriends.map((friend, i) => ( <div key={i} className={`user-item ${i === 0 ? "active" : ""}`}> <span className="chevron">❯</span> <span className="file-name">{friend.name}</span> </div> ))} </> ) }

Here I am passing fetched data from server component to client component. It is rendering and making API calls infinite times.

But when I return manual data without making any API request, example if I return return <><ChatSidebar friends={[{ name: "example1" }, { name: "example2" }, { name: "example3" }]} /></> it is working fine.

"use client" export default function ChatLayout({ children }: { children: React.ReactNode }) { return <> <div className="chat-layout"> {FriendsList()} {children} </div> </> }

Here is the layout I am using to render sidebar. Here while rendering FriendsList() it is also re-rendering the Parent Component i.e. Chatlayout component. This re-render triggers FriendsList() and it triggers parent re-render causing infinite re-renders.

Read Entire Article