-
I have a follow-up question on this issue, creating a new discussion as requested by @dai-shi. We also have the use-case of passing in props into a zustand store synchronously, because the backend delivers them to us in some cases. The solution from @drcmda looks like it would work well:
however, you would then only have access to your store inside this component. As far as I know, the general approach with zustand is that you export the How would you access this store created in your another approach might be to:
That would add one (inexpensive) render cycle, but it's not really synchronous. If I'm using other hooks in Do you maybe have a "best practices" approach for this? I'm leaning towards 1), but one advantage of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
(I recently recommend use-constant for lazy stable one-time memoization, instead of If you create a store with in a component (because of depending on props), and want to propagate it, then react context is the right solution. The second approach would also work. It's a global store with 2nd pass initialization, so to say. |
Beta Was this translation helpful? Give feedback.
(I recently recommend use-constant for lazy stable one-time memoization, instead of
useState
.)If you create a store with in a component (because of depending on props), and want to propagate it, then react context is the right solution.
However, passing a hook in context value has a pitfall. Unless it's not stable, we can violate rules of hooks.
To avoid the pitfall, we provide a special createContext in
zustand/context
. You can't violate rules of hooks with the special one.The second approach would also work. It's a global store with 2nd pass initialization, so to say.