Home  >  Q&A  >  body text

Next.js 13 - Jotai's useHydrateAtoms hook causes UI mismatch

<p>Working with Next.js 13 projects using the new application catalog and jotai as the global state manager. Now I'm trying to use the <code>useHydrateAtoms</code> hook to pass the initial state to my atoms as shown in the official documentation, but this results in a hydration error. </p> <p>The following is a simplified version of the code currently used, which passes the data received from the server-side component to the client-side component that calls <code>useHydrateAtoms</code> and uses <code>useAtom</ code> Read and write from this atom. </p> <h5>Server Component (Page)</h5> <pre class="brush:php;toolbar:false;">const getData = async () => { // ... } export default async function Page() { const data = await getData(); return <ChildComponent initialState={data} />; }</pre> <h5>Client component</h5> <pre class="brush:php;toolbar:false;">"use client"; export function ChildComponent({ initialState }) { useHydrateAtoms([[myAtom, initialState]]); const [data, setData] = useAtom(myAtom); return <>{data.id}</>; }</pre> <p>The error completely disappears when I dynamically import the subcomponent using <code>next/dynamic</code> and set the SSR option to false or remove the <code>useHydrateAtoms</code> hook, but both Both solutions defeat the purpose of this implementation. </p> <p>How do I provide an initial state to my atom using a value from the server so that the atom is not <code>null</code> on the first client render? </p>
P粉548512637P粉548512637439 days ago629

reply all(1)I'll reply

  • P粉495955986

    P粉4959559862023-08-30 13:38:02

    I discovered that useHydrateAtoms The hook itself is not the problem, it is a client component that accesses the state of different parts of the UI dynamically imported via next/dynamic ssr options set to false. This causes the value displayed by the component to change on the first render, resulting in a UI mismatch.

    How to fix the error

    Simply move the component that calls useHydrateAtoms to the top of the component tree, this will ensure that all child components will be rendered with the correct values.

    reply
    0
  • Cancelreply