Best Practices - Prop drill Jotai states or use useAtom
?
#2721
-
Hi, I have a simple question that I don't have the best answer for. When we create a new state, what is better? To pass the jotai state to the child component? or to redefine the state using useAtom? METHOD 1:// parent-component.tsx
const [count, setCount] = useAtom(countAtom);
return <>
<ChildComponent count={count} setCount={setCount}
</> METHOD 2:// child-component.tsx
const [count, setCount] = useAtom(countAtom); Which method has the best performance? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
If I understand correctly, in method 2 the parent component also uses Pedantic, method 1 is slightly better performance wise (or memory usage) because only the parent component needs to subscribe to the store and only the parent component will be rendered twice initially (see #1444). In practice, it's likely a negligible difference and you should do what feels better for your use case (e.g. use method 1 if you want make your child component reusable with different atoms / state, use method 2 if you want to use your child component in many places with always the same state). |
Beta Was this translation helpful? Give feedback.
-
If you're using the app router in next.js, and the parent component isn't using any hooks, then passing down as props would be more performant if the child also doesn't have any hooks since you can have the components be rendered server-side first. |
Beta Was this translation helpful? Give feedback.
If I understand correctly, in method 2 the parent component also uses
useAtom(countAtom)
, right?Pedantic, method 1 is slightly better performance wise (or memory usage) because only the parent component needs to subscribe to the store and only the parent component will be rendered twice initially (see #1444). In practice, it's likely a negligible difference and you should do what feels better for your use case (e.g. use method 1 if you want make your child component reusable with different atoms / state, use method 2 if you want to use your child component in many places with always the same state).