create-context
shadcn-hooks/create-contextFreeUtility
Create a context object.
Install it
npx shadcn@latest add https://shadcn-hooks.com/r/create-context.jsonSource
1import * as React from 'react'23function createContext<ContextValueType extends object | null>(4 rootComponentName: string,5 defaultContext?: ContextValueType,6) {7 'use no memo'8 const Context = React.createContext<ContextValueType | undefined>(9 defaultContext,10 )1112 const Provider: React.FC<ContextValueType & { children: React.ReactNode }> = (13 props,14 ) => {15 const { children, ...context } = props16 // Only re-memoize when prop values change1718 const value = React.useMemo(19 () => context,20 // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps, react-hooks/use-memo21 Object.values(context),22 ) as ContextValueType23 return <Context value={value}>{children}</Context>24 }2526 Provider.displayName = `${rootComponentName}Provider`2728 function useContext(consumerName: string) {29 const context = React.use(Context)30 if (context) return context31 if (defaultContext !== undefined) return defaultContext32 // if a defaultContext wasn't specified, it's a required context.33 throw new Error(34 `\`${consumerName}\` must be used within \`${rootComponentName}\``,35 )36 }3738 return [Provider, useContext] as const39}4041/* -------------------------------------------------------------------------------------------------42 * createContextScope43 * -----------------------------------------------------------------------------------------------*/4445type Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined46type ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope }47interface CreateScope {48 scopeName: string;49 (): ScopeHook50}5152function createContextScope(53 scopeName: string,54 createContextScopeDeps: CreateScope[] = [],55) {56 let defaultContexts: any[] = []5758 /* -----------------------------------------------------------------------------------------------59 * createContext60 * ---------------------------------------------------------------------------------------------*/6162 function createContext<ContextValueType extends object | null>(63 rootComponentName: string,64 defaultContext?: ContextValueType,65 ) {66 'use no memo'67 const BaseContext = React.createContext<ContextValueType | undefined>(68 defaultContext,69 )70 const index = defaultContexts.length71 defaultContexts = [...defaultContexts, defaultContext]7273 const Provider: React.FC<74 ContextValueType & {75 scope: Scope<ContextValueType>76 children: React.ReactNode77// … truncated
Files it writes
More from shadcn-hooks
All 58 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| create-effect-with-targetcreate-effect-with-target | shadcn-hooks | Utilities | Free | 1 dep | |
| is-browseris-browser | shadcn-hooks | Utilities | Free | no deps |
