How to Type Custom React Hooks :👈 👉:How to Type API Responses in React

How to Use Generics in React Components

How to Use Generics in React Components with TypeScript

1. What Are Generics?

Generics in TypeScript allow us to create reusable components, functions, and types that work with different data types without losing type safety.

Instead of writing separate components for strings, numbers, or objects, we can write one generic component that supports all these types.

Example:

function identity<T>(value: T): T {
    return value;
}
const name = identity<string>("React");
const age = identity<number>(25);
  • T represents a generic type parameter.
  • It acts as a placeholder for a type.
  • The actual type is determined when the function is used.

2. Why Use Generics in React?

Generics are useful when a component needs to work with different types of data.

For example, a reusable list component might display:

  • A list of strings.
  • A list of numbers.
  • A list of user objects.
  • A list of product objects.

Without generics, we might need separate components for each data type. With generics, we can create one reusable component.

3. Basic Generic React Component

Let's create a component that displays a list of items.

type ListProps<T> = {
    items: T[];
};
function List<T>({ items }: ListProps<T>) {
    return (
        <ul>
            {items.map((item, index) => (
                <li key={index}>{String(item)}</li>
            ))}
        </ul>
    );
}
export default List;

Using the component:

<List<string> items={["React", "Angular", "Vue"]} />
<List<number> items={[10, 20, 30]} />

TypeScript understands the type of items based on the generic parameter.

Note: The example uses String(item) so it can display primitive values. For object data, provide a rendering function.

4. Generic Component with Objects

Consider a component that displays a list of users.

type User = {
    id: number;
    name: string;
    email: string;
};
type ListProps<T> = {
    items: T[];
    renderItem: (item: T) => React.ReactNode;
};
function List<T>({ items, renderItem }: ListProps<T>) {
    return (
        <ul>
            {items.map((item, index) => (
                <li key={index}>
                    {renderItem(item)}
                </li>
            ))}
        </ul>
    );
}

Using the component:

const users: User[] = [
    { id: 1, name: "John", email: "john@example.com" },
    { id: 2, name: "David", email: "david@example.com" }
];
function App() {
    return (
        <List
            items={users}
            renderItem={(user) => (
                <div>
                    <strong>{user.name}</strong>
                    <p>{user.email}</p>
                </div>
            )}
        />
    );
}

TypeScript automatically understands that user is of type User. We don't need to explicitly specify its type in the callback.

5. Generic Components with Multiple Type Parameters

A generic component can accept more than one type parameter.

For example, a reusable dropdown might need one type for the option data and another for the selected value.

type DropdownProps<T, V> = {
    options: T[];
    getValue: (item: T) => V;
    getLabel: (item: T) => string;
    onChange: (value: V) => void;
};
function Dropdown<T, V>({
    options,
    getValue,
    getLabel,
    onChange
}: DropdownProps<T, V>) {
    return (
        <select
            onChange={(event) => {
                const selected = options.find(
                    item => String(getValue(item)) === event.target.value
                );
                if (selected) {
                    onChange(getValue(selected));
                }
            }}
        >
            {options.map((item, index) => (
                <option key={index} value={String(getValue(item))}>
                    {getLabel(item)}
                </option>
            ))}
        </select>
    );
}

Using the component:

type Product = {
    id: number;
    name: string;
};
const products: Product[] = [
    { id: 1, name: "Laptop" },
    { id: 2, name: "Mobile" }
];
function App() {
    return (
        <Dropdown
            options={products}
            getValue={(product) => product.id}
            getLabel={(product) => product.name}
            onChange={(id) => console.log(id)}
        />
    );
}
  • T: Represents the product object.
  • V: Represents the selected value, which is a number.

TypeScript infers both types from the supplied props.

6. Generic Components with Constraints

Sometimes we want a generic component to accept only objects that contain specific properties.

We can use the extends keyword to define constraints.

type HasId = {
    id: number;
};
type ListProps<T extends HasId> = {
    items: T[];
};
function List<T extends HasId>({ items }: ListProps<T>) {
    return (
        <ul>
            {items.map(item => (
                <li key={item.id}>
                    {item.id}
                </li>
            ))}
        </ul>
    );
}

Using the component:

type User = {
    id: number;
    name: string;
};
type Product = {
    id: number;
    productName: string;
};
<List<User> items={users} />
<List<Product> items={products} />

Both User and Product are accepted because they contain an id property.

The following type would not satisfy the constraint:

type Category = {
    name: string;
};
// Error: Category does not have the required id property.

When to use constraints:

  • When every item must have an ID.
  • When a component needs a specific property.
  • When building reusable tables, lists, and dropdowns.

7. Generic Data Table Component

A data table is a practical example of generics in React.

The same table component can display users, products, employees, or orders.

type Column<T> = {
    key: keyof T;
    title: string;
};
type TableProps<T> = {
    data: T[];
    columns: Column<T>[];
};
function DataTable<T extends { id: number }>({
    data,
    columns
}: TableProps<T>) {
    return (
        <table>
            <thead>
                <tr>
                    {columns.map(column => (
                        <th key={String(column.key)}>
                            {column.title}
                        </th>
                    ))}
                </tr>
            </thead>
            <tbody>
                {data.map(row => (
                    <tr key={row.id}>
                        {columns.map(column => (
                            <td key={String(column.key)}>
                                {String(row[column.key])}
                            </td>
                        ))}
                    </tr>
                ))}
            </tbody>
        </table>
    );
}

Using the component with users:

type User = {
    id: number;
    name: string;
    email: string;
};
const userColumns: Column<User>[] = [
    { key: "id", title: "ID" },
    { key: "name", title: "Name" },
    { key: "email", title: "Email" }
];
<DataTable<User>
    data={users}
    columns={userColumns}
/>

Using the same component with products:

type Product = {
    id: number;
    name: string;
    price: number;
};
const productColumns: Column<Product>[] = [
    { key: "id", title: "ID" },
    { key: "name", title: "Product Name" },
    { key: "price", title: "Price" }
];
<DataTable<Product>
    data={products}
    columns={productColumns}
/>

The same DataTable component works with different object types while preserving type safety.

8. Generic Components with React Hooks

Generics can also be used with React Hooks.

For example, consider a custom Hook that manages a list of any type.

import { useState } from "react";
function useList<T>(initialItems: T[] = []) {
    const [items, setItems] = useState<T[]>(initialItems);
    const addItem = (item: T) => {
        setItems(previous => [...previous, item]);
    };
    const removeItem = (index: number) => {
        setItems(previous =>
            previous.filter((_, i) => i !== index)
        );
    };
    return {
        items,
        addItem,
        removeItem
    };
}

Using the custom Hook:

function App() {
    const { items, addItem, removeItem } =
        useList<string>(["React", "TypeScript"]);
    return (
        <div>
            {items.map((item, index) => (
                <div key={index}>
                    {item}
                    <button onClick={() => removeItem(index)}>
                        Remove
                    </button>
                </div>
            ))}
            <button onClick={() => addItem("Angular")}>
                Add
            </button>
        </div>
    );
}

The same Hook can manage numbers, users, products, or other types.

9. Generic Components with Default Types

We can also provide a default type for a generic parameter.

type SelectProps<T = string> = {
    value: T;
    onChange: (value: T) => void;
};
function Select<T = string>({
    value,
    onChange
}: SelectProps<T>) {
    return (
        <button onClick={() => onChange(value)}>
            Select
        </button>
    );
}

Here, T defaults to string when no other type is inferred or specified.

Using different types:

<Select<string>
    value="React"
    onChange={(value) => console.log(value)}
/>
<Select<number>
    value={100}
    onChange={(value) => console.log(value)}
/>

10. Generic Components in TSX: Important Syntax

In a .tsx file, this syntax can be ambiguous:

const List = <T>(props: ListProps<T>) => {
    return null;
};

The TypeScript parser may interpret <T> as the beginning of JSX.

A common solution is to add a trailing comma:

const List = <T,>(props: ListProps<T>) => {
    return null;
};

Alternatively, use a function declaration:

function List<T>(props: ListProps<T>) {
    return null;
}

Both approaches are valid.

11. Common Mistakes

1. Using any Instead of Generics

Avoid:

type Props = {
    items: any[];
};

Better:

type Props<T> = {
    items: T[];
};

Generics preserve type information, whereas any removes much of TypeScript's type checking.

2. Forgetting to Declare the Generic Parameter

Incorrect:

type Props = {
    items: T[];
};
🔙
How to Type Custom React Hooks :👈 👉:How to Type API Responses in React

Comments and Discussion