Mastering React with Typescript: It’s Benefits and Importance

Karnika Gupta
Women in Technology
5 min readOct 4, 2023
React

Introduction

React with Typescript is a powerful combination for creating web applications. Typescript helps in giving static type in the react project which helps the developers in maintaining code quality and improves productivity. Let’s discuss the benefits and its usage in detail.

1. Setting up your development environment

You can set up your react project using create-react-app along with Typescript support:

npx create-react-app my-ts-app --template typescript

Use npm start to start your development server.

Create a component like:

// components/Hello.tsx
import React from 'react';

interface HelloProps {
name: string;
}

const Hello: React.FC<HelloProps> = ({ name }) => {
return <div>Hello, {name}!</div>;
};

export default Hello;

This is a functional component ‘Hello’ with ‘name’ as props.

2. Typescript fundamentals for react

It provides several ways to define type in react like interface or type or several others.

interface User {
id: number;
name: string;
}

type Product = {
id: number;
title: string;
};

You can also define types for states and props

interface TodoProps {
title: string;
completed: boolean;
}

class Todo extends React.Component<TodoProps, {}> {
// ...
}

Don’t worry, as we move forward, we’ll discuss about this in detail.

3. Functional components with typescript

type GreetingProps = {
name: string;
};

const Greeting: React.FC<GreetingProps> = ({ name }) => {
return <div>Hello, {name}!</div>;
};

In the above code, we have defined the type for props as GreetingProps where thename is given a type string. After that, we have the component named Greeting which is given a type React.FC and props are passed.

Hooks with typescript

import React, { useState, useEffect } from 'react';

const Counter: 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>
);
};

In the above code, we have used useState() and given it a type number as the initial value is 0 and it will store the number as a value.

4. Working with forms and events

const [formData, setFormData] = useState<{ username: string; password: string }>({
username: '',
password: '',
});

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// Process form data
};

In the given code, we have used a username and password and their state is an empty string. Type is given as a string as it will store string values.

const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
console.log('Button clicked!');
};

This code shows how you can handle button click event with Typescript.

5. State management with react and typescript

States in React with Typescript can be managed using React’s built-in states, Context API, and Redux.

interface AppState = {
user: User | null;
};

const initialState: AppState = {
user: null,
};

Here, we have defined an interface AppState which will contain all the types that are required. user is given a type User | null and in the function initialState the user has a value given as null. So there will be no type errors.

6. Advanced typescript patterns in react

interface MousePositionProps = {
render: (x: number, y: number) => React.ReactNode;
};

const MousePosition: React.FC<MousePositionProps> = ({ render }) => {
// Get mouse coordinates
const [x, setX] = useState(0);
const [y, setY] = useState(0);

useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
setX(e.clientX);
setY(e.clientY);
};

window.addEventListener('mousemove', handleMouseMove);

return () => {
window.removeEventListener('mousemove', handleMouseMove);
};
}, []);

return <div>{render(x, y)}</div>;
};

This is how we can render props in React using typescript. Here MousePositionProps is the interface where props are given their type. In the MousePosition component, MousePositionProps are given as types, and render is passed as props. The initial coordinates of mouse are set to 0 and the handleMouseMove function is defined to handle the mouse movement and set the coordinates according to it.

7. Code quality and performance optimization

Typescript Linting

We can use ESlint and TSlint in our React project to maintain code quality. This is the best practice while using typescript.

Performance Optimization

Using React.memo or useMemo so that the component rendering is optimized. Code splitting can be used for better application performance using typescript.

Benefits and Importance of Using Typescript

There are several benefits of using Typescript with React. Some of them are listed below:

1. Type Safety

  • Typescript adds the static types in react which helps in avoiding runtime errors that are caused by incorrect data types.
  • The type inference feature helps in automatically fetching the types in many cases.

2. Improved Code Quality

  • Typescript makes the code look more organized as all the types are defined and we know what should be the expected type.
  • One of the main benefits of using typescript is that it catches type errors on compile time which helps in avoiding the bugs and issues to reach the production code.

3. Enhanced Tooling

  • Typescript provides an auto-completion feature in modern code editors and IDEs (Integrated Development Environments) which improves the experience.

4. Better Collaboration

  • When dealing with large development teams, typescript helps in understanding each other’s code as the static types serve as documentation for functions and components. This helps in better collaboration among all the members.
  • Coding standards can be imposed to maintain code quality.

5. Improved Refactoring

  • When we refactor the code, there can be changes in the props or the structuring of the function. Typescript helps you in providing all the changes that are needed in the component to avoid any bugs.
  • This helps in updating the code and smooth refactoring of the code.

6. Enhanced IDE Support

  • Typescript is supported by almost all the IDEs. The most popular IDE that supports typescript is Visual Studio Code, which supports on-the-fly error checking, code navigation, and code refactoring tools.
  • Typescript also goes well with linters and other development tools.

7. Reduces Debugging Time

  • Typescript reduces debugging time as all the type errors are caught in the early stages and the error messages are well explained which helps the developers in resolving the errors early.

8. Long-term Maintenance

  • Typescript has a growing community that is evolving continuously. It remains compatible with the latest JavaScript and React updates so that it can support the projects for the long term.

Conclusion

Using typescript with react provides benefits in several ways as we discussed in this blog. These practices will make your developer’s productivity better by improving code quality, which in turn will make your React application more reliable and efficient.

--

--