How to Type React Event Handlers :👈 👉:How to Use Generics in React Components

How to Type Custom React Hooks

How to Type Custom React Hooks in TypeScript

1. Introduction

Custom Hooks allow us to reuse stateful logic between React components.

When using TypeScript, we can define the types of:

  • Custom Hook parameters.
  • Return values.
  • State variables.
  • Functions returned by Hooks.
  • Objects and arrays returned by Hooks.
  • Generic types for reusable Hooks.

TypeScript makes custom Hooks safer, easier to understand, and more reusable.

2. Creating a Simple Custom Hook

Let's start with a simple custom Hook that manages a counter.

Example

import { useState } from "react";
function useCounter() {
    const [count, setCount] = useState(0);
    const increment = () => {
        setCount(prev => prev + 1);
    };
    const decrement = () => {
        setCount(prev => prev - 1);
    };
    return {
        count,
        increment,
        decrement
    };
}
export default useCounter;

TypeScript automatically infers the types:

  • count is a number.
  • increment is a function returning void.
  • decrement is a function returning void.
  • The Hook returns an object containing these properties.

Important: You do not need to explicitly define every type when TypeScript can infer it correctly.

3. Using a Custom Hook in a Component

import useCounter from "./useCounter";
function App() {
    const {
        count,
        increment,
        decrement
    } = useCounter();
    return (
        <div>
            <h2>Count: {count}</h2>
            <button onClick={increment}>
                Increment
            </button>
            <button onClick={decrement}>
                Decrement
            </button>
        </div>
    );
}
export default App;

The component automatically receives the inferred types from the custom Hook.

4. Typing Custom Hook Parameters

When a custom Hook accepts parameters, define their types explicitly when necessary.

Example: useCounter with Initial Value

import { useState } from "react";
function useCounter(initialValue: number = 0) {
    const [count, setCount] = useState(initialValue);
    const increment = () => {
        setCount(prev => prev + 1);
    };
    return {
        count,
        increment
    };
}
export default useCounter;

Usage:

const counter = useCounter(10);

Here:

  • initialValue must be a number.
  • If no value is supplied, it defaults to zero.
  • The state value is inferred as a number.

5. Explicitly Typing the Return Value

For simple Hooks, TypeScript can infer the return type. However, explicitly defining the return type can be useful when the Hook has a public API that should remain consistent.

Example

interface CounterResult {
    count: number;
    increment: () => void;
    decrement: () => void;
}
function useCounter(): CounterResult {
    const [count, setCount] = useState(0);
    const increment = () => {
        setCount(prev => prev + 1);
    };
    const decrement = () => {
        setCount(prev => prev - 1);
    };
    return {
        count,
        increment,
        decrement
    };
}

Explanation:

  • CounterResult defines the Hook's return structure.
  • count must be a number.
  • increment and decrement must be functions.
  • : CounterResult ensures the returned object follows this contract.

6. Typing Custom Hooks with Objects

Suppose a Hook manages user information.

Example

import { useState } from "react";
interface User {
    id: number;
    name: string;
    email: string;
}
function useUser() {
    const [user, setUser] = useState<User | null>(null);
    const updateUser = (newUser: User) => {
        setUser(newUser);
    };
    const clearUser = () => {
        setUser(null);
    };
    return {
        user,
        updateUser,
        clearUser
    };
}
export default useUser;

Important: The state is initialized with null, but it can later contain a User object. Therefore, we use the union type User | null.

7. Typing Custom Hooks with Arrays

Custom Hooks can also return arrays.

Example

import { useState } from "react";
function useToggle(initialValue: boolean = false) {
    const [value, setValue] = useState(initialValue);
    const toggle = () => {
        setValue(prev => !prev);
    };
    return [value, toggle] as const;
}
export default useToggle;

Usage:

function App() {
    const [isOpen, toggle] = useToggle();
    return (
        <div>
            <p>{isOpen ? "Open" : "Closed"}</p>
            <button onClick={toggle}>
                Toggle
            </button>
        </div>
    );
}

Why use as const?

Without as const, TypeScript may infer a general array type whose elements have a union type. With as const, it infers a readonly tuple containing a boolean and a function.

8. Typing Custom Hooks with Generic Types

Generics allow us to create reusable Hooks that work with different data types.

For example, instead of creating separate Hooks for users, products, and orders, we can create one generic Hook.

Example: useArray

import { useState } from "react";
function useArray<T>(initialValue: T[] = []) {
    const [items, setItems] = useState<T[]>(initialValue);
    const addItem = (item: T) => {
        setItems(prev => [...prev, item]);
    };
    const removeItem = (index: number) => {
        setItems(prev =>
            prev.filter((_, i) => i !== index)
        );
    };
    const clearItems = () => {
        setItems([]);
    };
    return {
        items,
        addItem,
        removeItem,
        clearItems
    };
}
export default useArray;

Using the Generic Hook with Numbers

const numbers = useArray<number>([10, 20, 30]);
numbers.addItem(40);
// TypeScript error
numbers.addItem("Hello");

Using the Same Hook with Strings

const names = useArray<string>(["John", "David"]);
names.addItem("Robert");
// TypeScript error
names.addItem(100);

Explanation:

  • <T> represents a generic type.
  • T[] represents an array of that type.
  • addItem(item: T) accepts only the selected type.
  • The same Hook works with numbers, strings, objects, and other types.

9. Typing a Custom Hook with Loading and Error States

In real applications, Hooks frequently manage API requests.

We need to handle three important states:

  • Loading
  • Success
  • Error

Example: useFetch

import { useEffect, useState } from "react";
interface User {
    id: number;
    name: string;
    email: string;
}
function useFetchUsers() {
    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    useEffect(() => {
        const controller = new AbortController();
        async function fetchUsers() {
            try {
                setLoading(true);
                setError(null);
                const response = await fetch(
                    "/api/users",
                    { signal: controller.signal }
                );
                if (!response.ok) {
                    throw new Error("Failed to fetch users");
                }
                const data: User[] = await response.json();
                setUsers(data);
            } catch (err) {
                if (err instanceof Error &&
                    err.name !== "AbortError") {
                    setError(err.message);
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }
        fetchUsers();
        return () => {
            controller.abort();
        };
    }, []);
    return {
        users,
        loading,
        error
    };
}
export default useFetchUsers;

Explanation:

  • users is an array of User objects.
  • loading is a boolean.
  • error can be a string or null.
  • AbortController helps cancel the request when the effect is cleaned up.
  • The Hook returns all three values to the component.

Important: The User[] annotation on API data is a compile-time assertion, not runtime validation. Validate external API responses when their structure cannot be trusted.

10. Typing Custom Hooks with Callback Functions

Sometimes a custom Hook accepts a callback function as a parameter.

Example: useEventListener

import { useEffect } from "react";
function useEventListener(
    eventName: string,
    handler: (event: KeyboardEvent) => void
) {
    useEffect(() => {
        window.addEventListener(eventName, handler);
        return () => {
            window.removeEventListener(eventName, handler);
        };
    }, [eventName, handler]);
}
export default useEventListener;

Usage:

function App() {
    useEventListener("keydown", (event) => {
        console.log(event.key);
    });
    return <h2>Press any key</h2>;
}

This example illustrates callback typing. In production, ensure the callback type matches the selected event name, or define separate overloads or specialized Hooks for different event types. Also consider how callback identity affects effect cleanup and registration.

11. Typing Custom Hooks with Discriminated Unions

For more complex Hooks, a discriminated union can represent different states clearly.

Example: API Request State

type FetchState<T> =
    | {
        status: "loading";
    }
    | {
        status: "success";
        data: T;
    }
    | {
        status: "error";
        error: string;
    };

Now the component can handle each state safely:

function UserList({ state }: { state: FetchState<User[]> }) {
    if (state.status === "loading") {
        return <p>Loading...</p>;
    }
    if (state.status === "error") {
        return <p>{state.error}</p>;
    }
    return (
        <ul>
            {state.data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

TypeScript knows which properties are available based on the value of status.

12. Common Mistakes When Typing Custom Hooks

  1. Using any unnecessarily: Avoid any because it removes useful type checking.
  2. Forgetting null in state types: If state starts with null and later holds an object, use a union such as User | null.
  3. Returning an incorrectly typed array: Use as const when you intend to return a tuple with fixed positions and types.
  4. Overusing explicit return types: Let TypeScript infer straightforward return types.
  5. Ignoring generic types: Use generics when a Hook should work with multiple data types.
  6. Assuming API data is validated: Type annotations do not verify external data at runtime.
  7. Ignoring effect cleanup: Clean up subscriptions, timers, and event listeners when required.
  8. Breaking the Rules of Hooks: Call Hooks at the top level of React components or custom Hooks, not inside conditions or loops.

13. Best Practices

  • Name custom Hooks using the use prefix, such as useCounter and useFetchUsers.
  • Define interfaces or types for complex data structures.
  • Use TypeScript inference when it is clear and reliable.
  • Define explicit return types when they improve a reusable Hook's public contract.
  • Use generics to build reusable Hooks.
  • Represent loading, success, and error states clearly.
  • Use functional state updates when the next state depends on the previous state.
  • Handle effect cleanup when working with subscriptions, timers, and requests.
  • Keep each custom Hook focused on one reusable piece of logic.

14. Interview Questions and Answers

Q1. What is a custom Hook in React?

A custom Hook is a JavaScript function that uses React Hooks to share reusable stateful logic between components.

Q2. How do you type parameters in a custom Hook?

Define parameter types using TypeScript annotations.

function useCounter(initialValue: number) {
    // Hook logic
}

Q3. How do you define the return type of a custom Hook?

Use an interface, type alias, or let TypeScript infer the return type.

interface CounterResult {
    count: number;
    increment: () => void;
}
function useCounter(): CounterResult {
    // Hook logic
}

Q4. Why do we use generics in custom Hooks?

Generics allow a Hook to work with different data types while maintaining type safety.

Q5. How do you type a Hook that returns an array and a function?

Use a tuple type or as const to preserve the individual element types.

Q6. How do you represent nullable state in a custom Hook?

Use a union type such as User | null.

Q7. Should every custom Hook have an explicit return type?

No. TypeScript can infer many return types. Explicit return types are useful when defining stable public contracts or complex return structures.

Q8. Can a custom Hook call another custom Hook?

Yes. A custom Hook can call other Hooks, provided the Rules of Hooks are followed.

Q9. How do you type loading and error states?

Use a boolean for loading and a union such as string | null for a simple error state. Discriminated unions are useful for more complex request states.

Q10. Does TypeScript validate API responses in a custom Hook?

No. TypeScript provides compile-time type checking. Runtime validation requires a validation library or custom validation logic.

15. Key Takeaways

  • Custom Hooks allow reusable stateful logic.
  • Type Hook parameters using TypeScript annotations.
  • Use interfaces or types for complex objects.
  • TypeScript can automatically infer many Hook return types.
  • Use as const for fixed tuple return values.
  • Use generics to build reusable Hooks.
  • Use union types for nullable state and different states.
  • Handle loading, errors, and cleanup appropriately.
  • Follow the Rules of Hooks.

Remember: A well-typed custom Hook provides reusable logic with a clear contract. Define its inputs and outputs carefully, use generics when appropriate, and let TypeScript infer simple types whenever possible.

🔙
How to Type React Event Handlers :👈 👉:How to Use Generics in React Components

Comments and Discussion