reactjsnext.jsreact-server-components

NextJS 14 server component after pressing on passed function it starts to infinitely rerender


I am trying to make simple page with NextJS.

Simplified structure looks like this:

<page> // Client component
    <List onPress={val =\> setState(val)} \> // Server component
    <Modal> // Client component
<page>

List is done like this:

interface Props {
setEmbedId: (value: string) => void
}

export const ImagesList = async ({ setEmbedId }: Props) => {
const images = await getData() as ProjectData[]

return <div className="grid grid-cols-1 md:grid-cols-3">
    {images?.map(x => {
        return <div key={x.id}>
            <ImageCell onClick={() => {
                setEmbedId(x.videoUrl)
            }} title={x.title} description={x.description} />
        </div>
    })}
</div>
}

and the parent component is like this:

export default async function Home() {
const \[embedId, setEmbedId\] = useState("")
return <div onClick={() => console.log("asas")}>
<TopMenu />
<ImagesList setEmbedId={id => setEmbedId(id)} />
<ModalVideo embedId={embedId} onClose={() => { setEmbedId("") }} />
<About />
<Contacts />
</div>
}

If you have any info misisng please let me know :) Thanks

I tried to to code it myself but after setState is called its starts to rerender. even if I call it from root its starts to rerender. So to sum up after initial render any rerender cause the infinite rerender.

I tried googling and looking in Stack overflow for answer no luck.

I expect it not to rerender after I rerender parent.


Solution

  • I posted this as an answer, because other people may also need it.

    1. You can't pass anything from the client component to the server component
    2. Let alone passing data. Importing server component inside a client component is an anti-pattern

    As for your solution, i believe you can combine server and client component inside a server component, using composition pattern