All files / src/hooks createContextHook.ts

100% Statements 33/33
100% Branches 4/4
100% Functions 1/1
100% Lines 33/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 341x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 10x 10x 4x 4x 6x 10x 3x  
/**
 * @file createContextHook.ts
 * @description
 * Factory function for creating type-safe context access hooks.
 * Eliminates boilerplate by providing a reusable pattern for context consumption.
 *
 * @usage
 * const useMyContext = createContextHook(MyContext, 'useMyContext')
 * const value = useMyContext()
 */
 
import { useContext, type Context } from 'react';
 
/**
 * Create a type-safe hook for accessing a React context.
 * @param context - The React context to access (initialized with undefined)
 * @param hookName - Name of the hook (used in error message)
 * @returns A hook function that provides the context value or throws an error
 * @throws Error if used outside the context provider
 */
export function createContextHook<T>(
  context: Context<T | undefined>,
  hookName: string,
): () => T {
  // Return a hook function
  return (): T => {
    const value = useContext(context) as T | undefined;
    if (!value) {
      throw new Error(`${hookName} must be used within the corresponding provider`);
    }
    return value;
  };
}