-
I think I have a use case not sure if it's covered. I'm trying to replace a with useState const useHook = ({ initialCount = 2 }) => {
const [count, setCount] = useState(initialCount);
return { count }; // returns 2 from first render
}; with useAtom const myCountAtom = atom(0); // initial value should not be important
const useAtomHook = ({ initialCount = 2 }) => {
const [count, setCount] = useAtom(myCountAtom);
useEffect(() => {
setCount(initialCount);
}, []);
return { count }; // returns 0 on first render, then 2 after useEffect runs
}; ideally const myCountAtom = atom(0); // initial value is not important
const useAtomHook = ({ initialCount = 2 }) => {
const [count, setCount] = useAtom(myCountAtom, initialCount); //overwrites the atom value on first render
return { count }; // returns 2 on first render
}; Is there a util function I'm missing? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You could do this: const myCountAtom = atomFamily(initialValue => atom(initialValue));
const useAtomHook = ({ initialCount = 2 }) => {
const [count, setCount] = useAtom(myCountAtom(initialCount))
return { count }; // returns 2 on first render
}; however, the atom will need to be referenced by the original "initialValue", eg if you wanted to use it elsewhere, you'd have to pass |
Beta Was this translation helpful? Give feedback.
You could do this:
however, the atom will need to be referenced by the original "initialValue", eg if you wanted to use it elsewhere, you'd have to pass
2
(in this example) to the atomFamily.