Exploring Generics in React with TypeScript: A Practical Guide
As I delve deeper into React and TypeScript, I’ve recently learned about the power of generics. Generics allow us to create reusable components that can work with a variety of data types, making our code more flexible and type-safe. Today, I’d like to share a practical example of using generics in React.
Why Use Generics in React TypeScript?
Generics in TypeScript offer several benefits:
- Reusability: Create components that can handle various data types without duplicating code.
- Type Safety: Ensure that the correct data types are used, reducing runtime errors.
- Flexibility: Easily extend components to handle new data types as your application grows.
Basic Example
Let’s start with a simple component that can handle different types of items. We define a ListPropType
that can be an array of either strings or numbers.
type ListPropType = {
items: string[] | number[];
};
export const GenObject = ({ items }: ListPropType) => {
return (
<>
<h2>List Of Items</h2>
<div>
{items.map((item, idx) => <div key={idx}>{item}</div>)}
</div>
</>
);
};
In this example, GenObject
takes a prop called items
, which can be an array of strings or numbers. It maps over the items and displays each one.
Introducing Generics
To make our component even more flexible, we can use generics. Generics allow us to define components that work with any data type, not just strings or numbers.
But before that lets see TS generics ,
What are Generics in TypeScript?
Generics in TypeScript enable us to create functions, classes, and components that can work with a range of data types. They provide flexibility while maintaining type safety, ensuring that our code remains robust and predictable.
Let’s start with a simple generic function that echoes back whatever value is passed to it:
//infer type
function echo<T>(arg: T): T {
return arg;
}
// Usage examples
let result = echo<string>("Hello, TypeScript!"); // result is of type string
console.log(result); // Output: Hello, TypeScript!
let numberResult = echo<number>(42); // result is of type number
console.log(numberResult); // Output: 42
echo<T>
defines a generic function whereT
represents the type of the argument passed to the function and the return type.- We can call
echo
with different types (string
andnumber
in this case), and TypeScript infers and maintains the correct types forresult
andnumberResult
.
Now let’s come back to our React component where we will use TS generics
We can also use generics with primitive types like numbers and strings directly. This makes our component even more versatile.
type ListPropTypes<T> = {
items: T[];
};
export const GenComponent = <T extends number | string>({ items }: ListPropTypes<T>) => {
return (
<>
<h2>List Of Items</h2>
<div>
{items.map((item, idx) => <div key={idx}>{item}</div>)}
</div>
</>
);
};
You can try one example by own ,
Que — To Handle the JSON Object with generics .
Real-World Use Cases for Generics
Generics can be particularly useful in scenarios like:
- Form Handling: Creating a form component that can handle various field types.
- Data Tables: Developing a table component that can display different types of data.
- Reusable Hooks: Writing hooks that can work with multiple data types.
Using generics in React with TypeScript allows us to create highly reusable and flexible components. Whether we’re working with objects or primitive types, generics help us ensure type safety while keeping our code DRY (Don’t Repeat Yourself).
Feel free to share your thoughts or ask questions in the comments . Happy coding Follow For More !