You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I thought the docs tutorial was too complex for the average user so I decided to do a reusable createProvider function to make it easier to add new stores as your project grows. I decided to share with you guys and I hope you find it useful ☺️
CreateProvider.tsx
"use client";import{typeReactNode,createContext,useRef,useContext,typeFC,}from"react";import{useStore,typeStoreApi}from"zustand";import{useShallow}from"zustand/react/shallow";exportconstcreateProvider=<T,>(
createStore: () =>StoreApi<T>,
contextName: string,
) =>{constStoreContext=createContext<StoreApi<T>|undefined>(undefined);constStoreProvider: FC<{children: ReactNode}>=({ children })=>{conststoreRef=useRef<StoreApi<T>>(null);if(!storeRef.current){storeRef.current=createStore();}return(<StoreContext.Providervalue={storeRef.current}>{children}</StoreContext.Provider>);};constuseStoreSelector=<S,>(selector: (store: T)=>S): S=>{conststoreContext=useContext(StoreContext);if(!storeContext){thrownewError(`${contextName} must be used within its Provider`);}returnuseStore(storeContext,useShallow(selector));};return{ StoreProvider, useStoreSelector };};
Usage (Providers.tsx):
"use client";import{createProvider}from"@/lib/stores/CreateProvider";import{createCountStore,typeCountStore,}from"@/lib/stores/CountStore";const{StoreProvider: CountStoreProvider,useStoreSelector: useCountStore,}=createProvider<CountStore>(createCountStore,"CountStoreContext");
export functionProviders({ children }: {children: React.ReactNode}){return(<CountStoreProvider>{children}</CountStoreProvider>);}export{useCountStore};
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I thought the docs tutorial was too complex for the average user so I decided to do a reusable createProvider function to make it easier to add new stores as your project grows. I decided to share with you guys and I hope you find it useful☺️
CreateProvider.tsx
Usage (Providers.tsx):
Usage (page.tsx):
Beta Was this translation helpful? Give feedback.
All reactions