SolidJSS
SolidJS2y ago
1 reply
Blankeos

Is there a way to hydrate signals on the server?

I have an AuthContext. I just specifically want to hydrate my user signal in some routes. Is there a way to do this?

As far as I know, even in React I can't do this unless I bring in a separate library. Jotai actually does this using useHydrateAtoms. I'm wondering if there's something similar in SolidJS that I can use? (Not Solid Start specific).

https://jotai.org/docs/utilities/ssr

// imports...

export type AuthContextValue = {
  user: Accessor<{ id: string; username: string } | null>;
  loading: Accessor<boolean>;
  login: (username: string, password: string) => Promise<ReturnType<AuthContextValue['user']>>;
  logout: () => Promise<{ success: boolean }>;
  register: (username: string, password: string) => Promise<ReturnType<AuthContextValue['user']>>;
};

const AuthContext = createContext({
  user: () => null,
  loading: () => false,
  login: async (username: string, password: string) => null,
  logout: async () => ({ success: false }),
  register: async (username: string, password: string) => null
} as AuthContextValue);

export const useAuthContext = () => useContext(AuthContext);

export const AuthContextProvider: FlowComponent = (props) => {
  const [user, setUser] = createSignal<ReturnType<AuthContextValue['user']>>(null);
  const [loading, setLoading] = createSignal<boolean>(false);

  // ...

  return (
    <AuthContext.Provider
      value={{
        user,
        loading,
        register,
        login,
        logout
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};
Jotai
Jotai takes a bottom-up approach to global React state management with an atomic model inspired by Recoil. One can build state by combining atoms and renders are optimized based on atom dependency. This solves the extra re-render issue of React context and eliminates the need for memoization.
SSR — Jotai, primitive and flexible state management for React
Was this page helpful?