Next.js Discord

Discord Forum

Zustand state in a page component

Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
I'm experimenting with Zustand in an App router environment. So far I've been able to manage a global state for the user profile that initializes at root layout and syncs from server to client, but it doesn't work with page components.

My root layout initializes the profile state using server actions:

import { getProfile, getUser } from '../actions';
import { useProfileStore } from '../store';

export default async function RootLayout({
}: {
  children: React.ReactNode;
}) {
  const user = await getUser();                         // User from auth service, if logged in
  const profile = user ? await getProfile(user) : null; // User profile
  useProfileStore.setState({ profile });                // Initialize server state

  return (
      <ProfileStoreAdapter profile={profile} />         // Adapter for passing state to client

I can now read the state with useProfileStore().profile in client components and useProfileStore.getState().profile in server components that are not page components. In a server-side page component it doesn't work:

import { useProfileStore } from '@/app/store';

export default function ProfilePage() {
  const { profile } = useProfileStore.getState();
  return <h2>{}</h2>;

If I move the state into a child component, it works:

import { useProfileStore } from '@/app/store';

export default function ProfilePage() {
  return <Profile />;

function Profile() {
  const { profile } = useProfileStore.getState();
  return <h2>{}</h2>;

It seems like page components mount before root layout, so they're receiving the null state before initialization. Child server components seem to mount after root layout, at least in my case. It's not that big of a deal just to use child components, but I was wondering can it be possible to initialize the state before the page component gets mounted?

0 Replies