Could useHydrateAtoms hydrate derived atoms immediately? #3035
Replies: 3 comments
-
We can solve this problem by hydrate all derived atoms. useHydrateAtoms([[countAtom, dataFromServer], [derived1Atom, dataFromServer], [derived2Atom, dataFromServer]]) However, if the number of derived atoms is too large, handling them can become a bit troublesome... |
Beta Was this translation helpful? Give feedback.
-
It sounds like a designed limitation. Can you hydrate countAtom higher up in the tree? |
Beta Was this translation helpful? Give feedback.
-
We have confirmed in a large-scale application using a large number of derived atoms that simply hydrating the primitive atoms immediately updates the derived atoms as well, and the issue you pointed out does not occur. Below is a minimal working example. This works with Next.js v15. 'use client';
import { atom, Provider, useAtom } from 'jotai';
import { useHydrateAtoms } from 'jotai/utils';
const countAtom = atom();
const derived1Atom = atom((get) => get(countAtom));
const derived2Atom = atom((get) => get(countAtom));
const UseAtomComponent = () => {
useHydrateAtoms([[countAtom, 100]]);
const [derived1] = useAtom(derived1Atom);
const [derived2] = useAtom(derived2Atom);
return (
<div>
<p>Derived 1: {JSON.stringify(derived1)}</p>
<p>Derived 2: {JSON.stringify(derived2)}</p>
</div>
);
};
export default function Test() {
return (
<Provider>
<UseAtomComponent />
</Provider>
);
} If you can provide the complete code where the issue is reproducible, I’ll review it. |
Beta Was this translation helpful? Give feedback.
-
Currently, useHydrateAtoms will only directly hydrate explicitly given atoms, but derived atoms will not be immediately hydrated. As a result, during rendering, derived atoms may throw errors due to being undefined.
just like this, if we only
derived1Atom or derived2Atom may be undefined in render
Beta Was this translation helpful? Give feedback.
All reactions