0Pricing
React Academy · Lesson

Typing Context & Custom Hooks

Create typed context with default values and write custom hooks with explicit return types.

Typing Context & Custom Hooks is a free React Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Typed Context with createContext

Pass the context type and a default value to createContext. Use null as default when the context must be used inside a provider, and handle it with a guard.

interface AuthContextType {
  user: User | null;
  login: (credentials: Credentials) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | null>(null);

The Guard Hook Pattern

Create a custom hook that reads the context and throws if it's used outside its provider. This eliminates null checks at every call site.

export function useAuth(): AuthContextType {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
  return ctx;
}

Typing the Provider

The provider component wraps children and supplies the context value. Type the value object explicitly so TypeScript verifies it matches the context type.

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User | null>(null);

  const login = async (creds: Credentials) => {
    const u = await apiLogin(creds);
    setUser(u);
  };

  const logout = () => setUser(null);

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

Context with Default Value

When a sensible default exists (e.g., a theme), pass it directly to createContext so the context is never null and no guard hook is needed.

interface ThemeContextType { theme: 'light' | 'dark'; toggle: () => void; }

const ThemeContext = createContext<ThemeContextType>({
  theme: 'light',
  toggle: () => {},
});

export const useTheme = () => useContext(ThemeContext);

Typing Custom Hooks Return Values

Annotate the return type of custom hooks explicitly, or let TypeScript infer it. Explicit types serve as documentation and prevent accidental shape changes.

interface UseCounterReturn {
  count: number;
  increment: () => void;
  decrement: () => void;
  reset: () => void;
}

function useCounter(initial = 0): UseCounterReturn {
  const [count, setCount] = useState(initial);
  return {
    count,
    increment: () => setCount(c => c + 1),
    decrement: () => setCount(c => c - 1),
    reset: () => setCount(initial),
  };
}

Tuple Return Types

Hooks that return a pair (like useState) use tuples. Type them with as const or an explicit tuple type so destructuring infers correctly.

function useToggle(initial = false): [boolean, () => void] {
  const [value, setValue] = useState(initial);
  const toggle = useCallback(() => setValue(v => !v), []);
  return [value, toggle];
}

// Destructuring correctly infers types:
const [isOpen, toggleOpen] = useToggle();

Generic Custom Hooks

Custom hooks can be generic too. A generic useLocalStorage hook stores any serializable type with full type safety.

function useLocalStorage<T>(key: string, initialValue: T): [T, (val: T) => void] {
  const [stored, setStored] = useState<T>(() => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch { return initialValue; }
  });

  const setValue = (val: T) => {
    setStored(val);
    localStorage.setItem(key, JSON.stringify(val));
  };

  return [stored, setValue];
}

Typing useReducer

Define action types as discriminated unions and the state shape as an interface. TypeScript will enforce valid action types in the reducer.

interface State { count: number; status: 'idle' | 'loading'; }
type Action =
  | { type: 'INCREMENT' }
  | { type: 'SET_STATUS'; payload: State['status'] };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'INCREMENT': return { ...state, count: state.count + 1 };
    case 'SET_STATUS': return { ...state, status: action.payload };
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0, status: 'idle' });

Typing useCallback & useMemo

TypeScript infers types for useCallback and useMemo from the factory function. Annotate explicitly only when inference fails.

const handleChange = useCallback(
  (e: React.ChangeEvent<HTMLInputElement>) => {
    onChange(e.target.value);
  },
  [onChange]
);

const sorted = useMemo(
  () => [...items].sort((a, b) => a.name.localeCompare(b.name)),
  [items]
); // inferred as typeof items

Context Selector Pattern with Types

A typed selector hook takes a selector function and returns only the needed slice, preserving full type inference.

function useAuthSelector<T>(selector: (ctx: AuthContextType) => T): T {
  const ctx = useAuth();
  return selector(ctx);
}

// Usage — TypeScript infers User | null:
const user = useAuthSelector(ctx => ctx.user);

Avoiding any in Hooks

Never use any in custom hooks. Use generics, unknown with type guards, or specific interfaces to keep the type chain intact.

// Bad:
function useFetch(url: string): { data: any; loading: boolean } { ... }

// Good:
function useFetch<T>(url: string): { data: T | null; loading: boolean } {
  const [data, setData] = useState<T | null>(null);
  // ...
  return { data, loading };
}

Quick Check

What is the purpose of the guard hook pattern when typing React context?

Recap

Type context with an explicit interface and a null-guarding hook. Annotate custom hook return types with interfaces or tuple types, use generics for reusable hooks, and type useReducer with discriminated union actions to catch invalid dispatches at compile time.

Frequently asked questions

Is the “Typing Context & Custom Hooks” lesson free?

Yes — the full text of “Typing Context & Custom Hooks” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Typing Context & Custom Hooks”?

Create typed context with default values and write custom hooks with explicit return types. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Typing Context & Custom Hooks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Typing Props & Component Return Types
  2. Typing Events & Refs in TypeScript
  3. Generic Components & Utility Types
  4. Typing Context & Custom Hooks
← Back to React Academy