[React.js] - Part 3. Type-Safe React Components: A Beginner’s Guide Using TypeScript (.tsx)

Ace Lennox
React with TypeScript is an excellent combination for building robust and type-safe user interfaces. Components in React can be written with .tsx
files, where TypeScript enhances code reliability with static typing.
This guide will focus on creating and using function components in TypeScript.

What is a Component in React?
In React, a component is a reusable building block that renders UI. It accepts input data (via props
) and returns React elements to be displayed on the screen.
Types of Components in TypeScript
Stateless Function Components: Components without their own state.
Stateful Function Components: Components with internal state or behavior.
Creating a Function Component in .tsx
A function component is defined as a TypeScript function that returns JSX. Let’s dive into how you can write one:
Basic Stateless Component
interface GreetingProps {
name: string;
}
const Greeting = ({ name }: GreetingProps) => {
return <h1>Hello, {name}!</h1>;
};
export default Greeting;
Key Points:
Interface for Props:
GreetingProps
defines the shape ofprops
.Ensures the
name
prop is always astring
.
Usage:
import './App.css'
import Greeting from './components/Greeting'
function App() {
return (
<>
<Greeting name="KaizuTech.com"/>
</>
)
}
export default App
Adding State with useState
To make a component stateful, use the useState
hook.
import { useState } from "react";
const Counter = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
Key Points:
useState<number>
specifies the type of the state value (count
).The
setCount
function updates the state.
Managing Props with Default Values
You can define default values for props
in TypeScript:
interface ButtonProps {
label: string;
onClick?: () => void; // Optional prop
}
const Button = ({ label, onClick }: ButtonProps) => {
return <button onClick={onClick}>{label}</button>;
};
// Default props
Button.defaultProps = {
onClick: () => alert("Button clicked!"),
};
export default Button;
Using useEffect
for Side Effects
With TypeScript, you can manage side effects using the useEffect
hook:
import { useState, useEffect } from "react";
const Timer = () => {
const [seconds, setSeconds] = useState<number>(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup
}, []);
return <p>Elapsed Time: {seconds} seconds</p>;
};
export default Timer;
Key Points:
TypeScript ensures the
seconds
state is a number.The cleanup function prevents memory leaks.
Handling Props and State Together
For more complex components, you can combine props
and state
:
import { useState } from "react";
interface UserCardProps {
name: string;
age: number;
}
const UserCard = ({ name, age }: UserCardProps) => {
const [isHidden, setIsHidden] = useState<boolean>(false);
return (
<div>
<h1>{name}</h1>
{!isHidden && <p>Age: {age}</p>}
<button onClick={() => setIsHidden(!isHidden)}>
{isHidden ? "Show Age" : "Hide Age"}
</button>
</div>
);
};
export default UserCard;
Stateless vs. Stateful Components in TypeScript

Tips for Using TypeScript in React
Define Prop Types with Interfaces:
Use
interface
ortype
to defineprops
for better type safety.
Use Type Generics for State:
Specify the type of state variables to avoid errors.
Conclusion
Writing components in TypeScript (.tsx
) enhances your React development by providing type safety and better code maintainability. Whether you are building stateless or stateful components, TypeScript ensures your code is predictable, reliable, and robust.
Mastering TypeScript with React will help you create scalable applications with fewer bugs. Happy coding! 🚀
Source Code
The complete source code for this project is available on GitHub