Day 11: TypeScript with React (Basic Integration)
I am a MERN stack developer. Here to learn and share my knowledge to help other to grow.
Introduction
On Day 11, we'll explore integrating TypeScript with React. TypeScript enhances React development by adding type safety, making it easier to catch errors early and improve code quality. We'll cover the basics of setting up a TypeScript project with React, typing React components, and handling props and state.
1. Setting Up a TypeScript Project with React
To start using TypeScript with React, you need to create a React project and configure TypeScript.
1.1. Create a React Project with TypeScript
You can use Create React App (CRA) to set up a new React project with TypeScript.
Steps:
Create a new React app with TypeScript:
npx create-react-app my-app --template typescriptNavigate to the project directory:
cd my-appStart the development server:
npm start
Your new React project will now be set up with TypeScript.
2. Typing React Components
TypeScript allows you to type your React components to ensure that props and state conform to specific types.
2.1. Typing Functional Components
You can define types for the props of a functional component using FC (Functional Component) or by defining your own type for props.
Example:
import React from 'react';
// Define a type for props
type GreetingProps = {
name: string;
age?: number; // Optional prop
};
// Functional component using typed props
const Greeting: React.FC<GreetingProps> = ({ name, age }) => {
return (
<div>
<h1>Hello, {name}!</h1>
{age && <p>You are {age} years old.</p>}
</div>
);
};
export default Greeting;
In this example, GreetingProps defines the shape of the props for the Greeting component.
2.2. Typing Class Components
Class components can also be typed by extending React.Component and providing types for props and state.
Example:
import React, { Component } from 'react';
// Define types for props and state
type CounterProps = {
initialCount: number;
};
type CounterState = {
count: number;
};
class Counter extends Component<CounterProps, CounterState> {
constructor(props: CounterProps) {
super(props);
this.state = {
count: props.initialCount
};
}
increment = () => {
this.setState(prevState => ({ count: prevState.count + 1 }));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
3. Typing React Hooks
React hooks, such as useState and useEffect, can also be typed to ensure type safety in functional components.
3.1. Typing useState
You can type the state managed by the useState hook to ensure type safety.
Example:
import React, { useState } from 'react';
const Counter: React.FC = () => {
// Typing useState
const [count, setCount] = useState<number>(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default Counter;
3.2. Typing useEffect
The useEffect hook can be typed to manage side effects with the appropriate dependencies.
Example:
import React, { useState, useEffect } from 'react';
const DataFetcher: React.FC = () => {
const [data, setData] = useState<string | null>(null);
useEffect(() => {
// Simulate fetching data
setTimeout(() => {
setData('Fetched Data');
}, 1000);
}, []); // Empty dependency array
return <div>{data ? data : 'Loading...'}</div>;
};
export default DataFetcher;
4. Handling Props and State
In React with TypeScript, handling props and state involves defining appropriate types and ensuring that components receive and manage data correctly.
4.1. Defining Prop Types
Define prop types using TypeScript interfaces or type aliases. Ensure that all required props are provided and optional props are handled gracefully.
4.2. Managing State Types
Define state types to maintain consistency and type safety in components. Ensure that state transitions are correctly typed and handled.
5. Practical Exercises
5.1. Creating a Typed Functional Component
Create a new file named
UserCard.tsx.Define a functional component that takes
nameandageas props and displays them.
Example Solution:
// UserCard.tsx
import React from 'react';
type UserCardProps = {
name: string;
age: number;
};
const UserCard: React.FC<UserCardProps> = ({ name, age }) => {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
};
export default UserCard;
5.2. Typing State in a Functional Component
Create a new file named
CounterWithHooks.tsx.Implement a counter component using
useStateanduseEffect.
Example Solution:
// CounterWithHooks.tsx
import React, { useState, useEffect } from 'react';
const CounterWithHooks: React.FC = () => {
const [count, setCount] = useState<number>(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default CounterWithHooks;
6. Conclusion
Today, we explored how to integrate TypeScript with React. You learned how to set up a TypeScript project with React, type functional and class components, and handle props and state with type safety. This integration ensures your React applications are more reliable and maintainable.

