UNPKG

@modern-kit/react

Version:
1 lines 2.08 kB
{"version":3,"file":"index.cjs","sources":["../../../src/hooks/useSafeContext/index.ts"],"sourcesContent":["import { invariant } from '@modern-kit/utils';\nimport { Context, useContext } from 'react';\n\n/**\n * @description React Context에 안전하게 접근하기 위한 훅입니다.\n *\n * Context에 기본값이 없다면(null/undefined) Provider 내부에서 사용되지 않았을 때 에러를 발생시킵니다.\n * Context에 기본값이 있다면 Provider 내부에서 사용되지 않았을 때 에러가 발생하지 않고 기본값을 반환합니다.\n *\n * 에러가 발생하지 않으면 안전하게 접근했기 때문에 NonNullable한 Context 값을 반환합니다.\n *\n * @template T - Context 타입\n *\n * @param {Context<T>} context - React Context\n * @returns {NonNullable<T>} NonNullable한 Context 값을 반환합니다.\n *\n * @throws Context의 기본값이 없는 상태에서 Provider 내부에서 사용되지 않았을 때 발생합니다.\n *\n * @example\n * ```tsx\n * const ThemeContext = createContext<{ theme: string } | null>(null);\n *\n * function MyComponent() {\n * const context = useSafeContext(ThemeContext);\n * // 안전하게 접근했기 때문에 context는 NonNullable 타입을 보장합니다.\n *\n * return <div>현재 테마: {context.theme}</div>;\n * }\n *\n * <ThemeContext.Provider value={{ theme: 'dark' }}>\n * <MyComponent />\n * </ThemeContext.Provider>\n * ```\n */\nexport function useSafeContext<T>(context: Context<T>): NonNullable<T> {\n const contextValue = useContext(context);\n const displayName = context.displayName ?? 'SafeContext';\n\n invariant(\n contextValue,\n `[${displayName}]: Provider 내부에서 사용되어야 합니다.`\n );\n\n return contextValue as NonNullable<T>;\n}\n"],"names":["useContext","invariant"],"mappings":";;;;;AAkCO,SAAS,eAAkB,OAAA,EAAqC;AACrE,EAAA,MAAM,YAAA,GAAeA,iBAAW,OAAO,CAAA;AACvC,EAAA,MAAM,WAAA,GAAc,QAAQ,WAAA,IAAe,aAAA;AAE3C,EAAAC,eAAA;AAAA,IACE,YAAA;AAAA,IACA,IAAI,WAAW,CAAA,uFAAA;AAAA,GACjB;AAEA,EAAA,OAAO,YAAA;AACT;;;;"}