codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🔷

TypeScript

60 / 60 topics
59TypeScript in the Real World60TypeScript with React
Tutorials/TypeScript/TypeScript with React
🔷TypeScript

TypeScript with React

Updated 2026-05-15
10 min read

TypeScript with React

Introduction

In the world of web development, JavaScript has been a staple language for building dynamic and interactive user interfaces. However, as projects grow in complexity, managing large codebases can become challenging. This is where TypeScript comes into play. TypeScript is a statically typed superset of JavaScript that adds optional types to the language, making it easier to catch errors early in the development process.

React, on the other hand, is a popular library for building user interfaces. It allows developers to create reusable UI components and manage state efficiently. Combining TypeScript with React can significantly enhance the robustness and maintainability of your applications.

In this tutorial, we will explore how to use TypeScript in React applications, covering everything from setting up a project to writing type-safe components.

Concept

Setting Up a TypeScript React Project

To start using TypeScript with React, you need to set up a new project or convert an existing one. The easiest way to do this is by using Vite, which provides a fast and modern environment for building web applications.

Terminal
npm create vite@latest my-ts-app --template react-ts

This command creates a new React application with TypeScript support. Once the setup is complete, you can navigate into your project directory:

cd my-ts-app

Basic Types in React

TypeScript introduces several useful types that are particularly helpful when working with React components.

Props and State

Props (properties) are used to pass data from a parent component to a child component. In TypeScript, you can define the shape of props using an interface or a type alias.

TypeScript
1interface AppProps {
2title: string;
3count: number;
4}
5
6function App({ title, count }: AppProps) {
7return (
8 <div>
9 <h1>{title}</h1>
10 <p>Count: {count}</p>
11 </div>
12);
13}

State is used to manage the internal data of a component. You can define the shape of state similarly using interfaces or type aliases.

TypeScript
1interface AppState {
2items: string[];
3}
4
5function App() {
6const [state, setState] = React.useState<AppState>({ items: [] });
7
8return (
9 <div>
10 <ul>
11 {state.items.map((item, index) => (
12 <li key={index}>{item}</li>
13 ))}
14 </ul>
15 </div>
16);
17}

Event Handling

React events are handled using event handler functions. TypeScript allows you to specify the type of event and the expected properties.

TypeScript
1function App() {
2const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
3 console.log('Button clicked:', event.currentTarget.value);
4};
5
6return (
7 <div>
8 <button onClick={handleClick} value="Submit">Click Me</button>
9 </div>
10);
11}

Advanced Types

TypeScript also provides advanced types that can be used to enhance the type safety of your React components.

Generics

Generics allow you to create reusable components that can work with different data types. This is particularly useful when building generic UI components.

TypeScript
1interface ListProps<T> {
2items: T[];
3}
4
5function List<T>({ items }: ListProps<T>) {
6return (
7 <ul>
8 {items.map((item, index) => (
9 <li key={index}>{String(item)}</li>
10 ))}
11 </ul>
12);
13}

Utility Types

TypeScript includes several utility types that can simplify common type operations. For example, the Partial type makes all properties of an interface optional.

TypeScript
1interface User {
2name: string;
3age: number;
4}
5
6function updateUser(user: Partial<User>) {
7// Update user logic here
8}

Examples

Example 1: Creating a Type-Safe Form Component

Let's create a simple form component that uses TypeScript to ensure type safety.

TypeScript
1interface FormData {
2name: string;
3email: string;
4}
5
6function Form() {
7const [formData, setFormData] = React.useState<FormData>({
8 name: '',
9 email: ''
10});
11
12const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
13 const { name, value } = event.target;
14 setFormData(prevState => ({
15 ...prevState,
16 [name]: value
17 }));
18};
19
20return (
21 <form>
22 <input type="text" name="name" value={formData.name} onChange={handleChange} />
23 <input type="email" name="email" value={formData.email} onChange={handleChange} />
24 <button type="submit">Submit</button>
25 </form>
26);
27}

Example 2: Using Context with TypeScript

Context is a powerful feature in React that allows you to pass data through the component tree without having to pass props down manually. Let's create a context for user authentication.

TypeScript
1interface AuthContextType {
2isAuthenticated: boolean;
3login: () => void;
4logout: () => void;
5}
6
7const AuthContext = React.createContext<AuthContextType>({
8isAuthenticated: false,
9login: () => {},
10logout: () => {}
11});
12
13function AuthProvider({ children }: { children: React.ReactNode }) {
14const [isAuthenticated, setIsAuthenticated] = React.useState(false);
15
16const login = () => {
17 setIsAuthenticated(true);
18};
19
20const logout = () => {
21 setIsAuthenticated(false);
22};
23
24return (
25 <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
26 {children}
27 </AuthContext.Provider>
28);
29}
30
31function AuthStatus() {
32const authContext = React.useContext(AuthContext);
33
34return (
35 <div>
36 <p>Authentication Status: {authContext.isAuthenticated ? 'Logged In' : 'Logged Out'}</p>
37 <button onClick={authContext.isAuthenticated ? authContext.logout : authContext.login}>
38 {authContext.isAuthenticated ? 'Logout' : 'Login'}
39 </button>
40 </div>
41);
42}

Conclusion

TypeScript is a powerful tool that can significantly improve the quality and maintainability of your React applications. By using TypeScript, you can catch errors early in the development process, making your code more robust and easier to understand.

In this tutorial, we covered the basics of setting up a TypeScript React project with Vite, defining types for props and state, handling events, and using advanced TypeScript features like generics and utility types. We also provided practical examples of creating type-safe form components and using context with TypeScript.

By incorporating TypeScript into your React projects, you can take advantage of its static typing capabilities to build more reliable and efficient applications.


PreviousTypeScript in the Real World

Recommended Gear

TypeScript in the Real World