SSR Usage - useHydrateAtoms
hook causes a UI missmatch
#1982
-
Working on a Next.js 13 project using the new app directory and jotai as global state manager. Now I am trying to pass an initial state to my atoms using the Following is an simplified version of the code that is currently used, it passes the data received from the server side component to a client component that calls Server component (page)const getData = async () => {
// ...
}
export default async function Page() {
const data = await getData();
return <ChildComponent initialState={data} />;
} Client component"use client";
export function ChildComponent({ initialState }) {
useHydrateAtoms([[myAtom, initialState]]);
const [data, setData] = useAtom(myAtom);
return <>{data.id}</>;
} When I dynamically import the child component using If not like this, how can one provide an initial state to an atom with a value from the server, so the atom is not |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
Is it null? because, your usage seems correct. Can anyone help on this? |
Beta Was this translation helpful? Give feedback.
@wootra I have discovered that the
useHydrateAtoms
hook was not the issue per-se, but if understood correctly it was a client component accessing the state in a different part of the UI imported dynamically vianext/dynamic
with thessr
option set to false. This caused the value displayed by the component to change on first render, what in return caused a UI mismatch.How to I fixed the error
Simply move the component that calls useHydrateAtoms to the top of the component tree, this will ensure that all children will render with the correct value.