How to Use React forwardRef with Generics

This article shows how to combine React forwardRef with TypeScript generics to build a reusable, type‑safe Table component while preserving full type inference using type assertions.

CChia1104
Notes1 minutes read

Since React's forwardRef is a HOC (Higher Order Component), we can't directly write generics inside the component. The most common scenario where I need to use generics and also reference internal methods is the Table component.

If we want to create a type-safe component, we can use the following approach:

  • We can use type assertion to make a forwardRef component support generics while preserving type inference.
export interface Props<TData> {
	data: TData[];
}

export interface Ref<TData> {
	table: Table<TData>;
}

const DataTableWithGeneric<TData>(
    props: Props<TData>, 
    ref: Ref<TData>
) => {
    React.useImperativeHandle(ref, () => ({
		table,
	}));

    const table = useReactTable({
		data: props.data,
	});

    return (
        // ...table component
    )
}

const Forwarded = React.forwardRef(DataTableWithGeneric) as <TData>(
	props: Props<TData> & {
		ref?: React.ForwardedRef<Ref<TData>>;
	},
) => ReturnType<typeof DataTableWithGeneric>;

export const DataTable = Forwarded;

Written by: Chia1104 CC BY-NC-SA 4.0

Chia1104
©
Chia1104