Next.js Discord

Discord Forum

Share state between client components with a server component as direct parent

Unanswered
Orinoco Crocodile posted this in #help-forum
Open in Discord
Avatar
Orinoco CrocodileOP
I'm trying to share the state between two client components where the parent component is a server component. My specific use case is showing and hiding an overlay at the same time as showing and hiding a map marker. Is there no way to do this or do I just need to duplicate the code across both components?
Image

5 Replies

Avatar
American
i think u can use context or state management like ( redux or zustand) personaly i prefer using zustand
Avatar
not-milo.tsx
React's context api is the simplest most straightforward way to do this.

Basically you create a context provider that holds the state you need and wrap both client components in it.
Avatar
Orinoco CrocodileOP
wouldn't using context make the parent component no longer be a server component?
Avatar
not-milo.tsx
No, that stays a server component
Nesting client components in server components is ok and using context to wrap pieces of your UI doesn't impact the server side of things.

Just remember that you cannot import a server component inside a client one, but only pass it as props (e.g. children)