How to Use TypeScript in React Apps (2023)

/ #Typescript
How to Use TypeScript in React Apps (1)
Germán Cocca
How to Use TypeScript in React Apps (2)

Hi everyone! A while ago I wrote an article about TypeScript, explaining its main features and why it's a good idea to use it in large projects.

Today we're going to take a quick look at how we can use TypeScript in a React app, so you can get an idea of how the implementation might look like and what are its benefits.

Table of Contents

  • Intro to TypeScript
  • How to Type Props
  • How to Type Hooks
    • Typing the useState hook
    • Typing the useRef hook
  • Wrap up

Intro to TypeScript

So by now you should know that TypeScript is a superset of JavaScript. Superset means that it adds features on top of what JavaScript offers.

TypeScript takes all the functionalities and structures JavaScript provides as a language, and adds a few things to that. The main thing TypeScript provides is static typing.

When it comes to React, besides everything we can type in vanilla JS (like variables, function parameters and return values, etc.), we can mainly use TypeScript to type two things: component props and hooks.

One of the simplest ways to create a React app with TypeScript is to use CRA, running npx create-react-app my-app --template typescript.

If you already have a CRA app created, in the docs you have info on how to install TypeScript on top of that. ;)

Also, for the examples here we're going to use CRA since it's nice and simple. But keep in mind that most frameworks like Next, Vite and Astro also provide support for TypeScript.

So after running CRA's script you'll have a project that looks somewhat like this:

How to Use TypeScript in React Apps (3)

As you can see, files are now named .tsx which is how TypeScript's compiler identifies you'll be using TypeScript in that file.

(Video) How to use TypeScript with React... But should you?

And besides, we have a tsconfig.json which is where we have all the compiler's config. You can learn more about that in the previous article I wrote.

Now let's create a component and see how we can put TypeScript to use.

How to Type Props

For this example we will set up a dummy component responsible for rendering a number received as props, and adding to that number when a button gets clicked.

Regular JavaScript code would look something like this:

const DummyComponent = ({ number, setNumber }) => { return ( <> <div>{number}</div> <button onClick={() => setNumber(prev => prev+1)} > ADD </button> </> )}export default DummyComponent

And our fully typed version will look like this:

import React, { Dispatch, SetStateAction } from 'react'interface DummyProps { number: number setNumber: Dispatch<SetStateAction<number>>}const DummyComponent:React.FC<DummyProps> = ({ number, setNumber }) => { return ( <> <div>{number}</div> <button onClick={() => setNumber(prev => prev+1)} > ADD </button> </> )}export default DummyComponent

You can see that next to the component name, we have added colons and React.FC. This basically tells the TypeScript component that DummyComponent is a React functional component. That itself doesn't do much, but it helps with TypeScript's intellisense.

Next to that we declared <DummyProps>. This declares that the props object that this component will receive must match the interface DummyProps.

An interface is TypeScript's way to type an object. Basically we declare all the properties that object will have, and the type for each of them.

Since this component will receive a state which is a number, and a function to update that state, that's exactly what we have within our interface:

interface DummyProps { number: number setNumber: Dispatch<SetStateAction<number>>}

Here you can see that for the setNumber function we're using this type: Dispatch<SetStateAction>. This is not a type native to TypeScript, but instead it's provided by React itself. So we have to import it each time we use it, like this:
import React, { Dispatch, SetStateAction } from 'react'.

And that's it! You have typed your props now. What's cool about this is each time you call that component, you'll get intellisense about the props that component expects. Same as if you try to pass a prop not declared in the component's interface or provide a wrong type for an expected prop.

How to Use TypeScript in React Apps (4)
How to Use TypeScript in React Apps (5)
How to Use TypeScript in React Apps (6)

This is what people mean when they say TypeScript self-documents your code. With just a few lines of boilerplate, now you can easily see what each component expects and doesn't. This comes in very handy when working in large projects, with hundreds of components which were written mostly by other people. ;)

How to Type Hooks

When it comes to hooks, TypeScript is mostly used to type useState and useRef hooks. Let's see how that works.

(Video) React & TypeScript - Course for Beginners

Typing the UseState hook

This is what useState looks like without types:

const [number, setNumber] = useState<>(0)

And with types it looks like this:

const [number, setNumber] = useState<number>(0)

Almost no need to explain, right? We just declare the type of the state value like this: <number> and that's it. If we ever try to update that state with a different value type, we'll get a nice red error message to prevent us from shooting ourselves in the foot. ;)

How to Use TypeScript in React Apps (7)

Keep in mind that if want to allow our state to hold different value types, we can declare that like this: const [number, setNumber] = useState<number | string>(0).

Now we can pass either a number OR a string without getting errors.

Typing the UseRef hook

useRef is a hook mainly used for referencing DOM elements on React. If you want to learn more about how the hook works, you can read this guide I recently wrote.

To see how we can implement it with TypeScript, we'll use this example:

import React, { useEffect, useRef } from 'react'const DummyComponent:React.FC = () => { const ref = useRef<HTMLInputElement>(null) useEffect(() => { if (ref.current) ref.current.focus() }, []) return ( <input type="text" ref={ref} /> )}export default DummyComponent

As you can see, we're initiating the ref variable with null and declaring its type as HTMLInputElement. When using the useRef hook and declaring its type, the variable can be assigned either to null or the declared type.

Then we have a useEffect hook that focuses the element if it has a current property. And lastly we're returning an input element and assigning the reference we previously declared: ref={ref}.

The cool thing about typing the useRef hook is that TypeScript will prevent us from trying to perform actions or read data from types that don't match.

For example, if we declared the type number for the ref, we would get the following errors:

How to Use TypeScript in React Apps (8)
How to Use TypeScript in React Apps (9)

Again, this is nice because it avoids silly errors ahead of time and saves us from having to debug this stuff later on. Especially when working with large codebases where many other people also work on, TypeScript gives us a more controlled and ordered environment to work in.

Wrap up

Well everyone, as always, I hope you enjoyed the article and learned something new.

(Video) React Typescript Setup Tutorial

If you'd like a deeper take on this topic, I recommend this video by Firebase or this other one be Ben Awad.

If you want, you can also follow me on LinkedIn or Twitter. See you in the next one!

How to Use TypeScript in React Apps (10)

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

(Video) Build a Complete Typescript React Fitness Application for Beginners | Responsive

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

How to Use TypeScript in React Apps (11)
Germán Cocca

I'm a fullstack dev (javascript | typescript | react | node | AWS) and computer engineering student. Here I write about the things I learn along my path to becoming the best developer I can be.

If you read this far, tweet to the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTISEMENT

(Video) Learn Typescript with React | Quick Crash Course

FAQs

Is it good practice to use TypeScript in React? ›

Using TypeScript with React provides several advantages in application-building, including the option of simpler React components and better JavaScript XML (JSX) support for static type validation.

How do I use React app with TypeScript? ›

To start a new Create React App project with TypeScript, you can run:
  1. npx create-react-app my-app --template typescript. ...
  2. yarn create react-app my-app --template typescript. ...
  3. npm install --save typescript @types/node @types/react @types/react-dom @types/jest.
Jan 12, 2022

How do you master TypeScript with React? ›

React Tutorial using TypeScript
  1. Uses TypeScript.
  2. Uses only function components with Hooks.
  3. Uses a pre-built Node.js REST API as a backend to do CRUD operations.
  4. Uses React Router.
  5. After getting it working, refactor your code to use Redux.
  6. Test the application using React Testing Library.

Can I develop in React with TypeScript? ›

If you're building a new app and using create-react-app , the docs are great: You can start a new TypeScript app using templates. To use our provided TypeScript template, append --template typescript to the creation command.

Why not to use TypeScript in React? ›

Here are some of the downsides: Typescript will take more time to learn and master, which can create delays in the execution of deadlines. There are certain JavaScript concepts that Typescript doesn't have, so you'll need to know another language like Java or C# in order to write code with those features.

Is React TypeScript faster than JavaScript? ›

TypeScript compiles down to JavaScript, meaning the TS code you write will be converted into JS before running. This provides faster execution times than JS since all the work is done ahead of time.

Why TS is better than JS? ›

Is TypeScript better than JavaScript? TypeScript is better than JavaScript in terms of language features, reference validation, project scalability, collaboration within and between teams, developer experience, and code maintainability.

Should I use React with JS or TypeScript? ›

While JavaScript is a great language, TypeScript has many features that make it a better choice when working with React. With TypeScript, you get type safety, better IDE support, improved maintainability, easier refactoring, and a large and active community.

What is the difference between TypeScript and JSX? ›

TypeScript is a language that is a syntactic-superset of JavaScript. JSX is FaceBook's XML-like syntax extension to JavaScript, not a language per se. @vbguyny what you have provided as information is regarding TypeScript and Facebook JSX extention which has nothing to do with the DeNA JSX.

How long to learn TypeScript with React? ›

How long it will take to learn typescript as react developer? As a mid-level React developer, it only took me four days to implement TypeScript in my React project.

How long does it take to master TypeScript? ›

How Long Does it Take to Learn TypeScript? It takes about a month to learn the basics of TypeScript, assuming you study for at least one hour a day. Expect to spend at least six months studying TypeScript before you develop the skills you need to apply it in a professional development setting.

How long does it take to learn React and TypeScript? ›

If TypeScript is your first language, it will likely take you anywhere from 3 months to a year to learn. Mainly because you need to learn JavaScript and type systems as well! However, if you understand JavaScript and how type systems work, you can easily get the basics of TypeScript down within a day to a week.

Is it OK to mix TypeScript and JavaScript? ›

Yes, you can use TypeScript and JavaScript together in the same project. TypeScript is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code.

Is it possible to mix TypeScript and JavaScript? ›

It is possible to have mixed TypeScript and JavaScript projects. To enable JavaScript inside a TypeScript project, you can set the allowJs property to true in the tsconfig.json .

What is disadvantage of TypeScript? ›

Disadvantages of TypeScript as compared to JavaScript

TS takes a long time to compile the code. TS doesn't support abstract classes. When using a third party library, there needs to be a definition file, and sometimes it's not always available. Quality of type definition files is a concern.

Is it bad practice to use as in TypeScript? ›

Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.

Should I skip JavaScript for TypeScript? ›

We frequently see the question “Should I learn JavaScript or TypeScript?“. The answer is that you can't learn TypeScript without learning JavaScript! TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time.

Is TypeScript strong or weak typing? ›

In particular, TypeScript is strongly typed — that is, variables and other data structures can be declared to be of a specific type, like a string or a boolean, by the programmer, and TypeScript will check the validity of their values. This isn't possible in JavaScript, which is loosely typed.

Is TypeScript the future of JS? ›

With its continuously evolving potential, these incredible benefits of TypeScript over JavaScript make TS the first choice for today's developers. One can see the booming potential of TS language over JS, making it the future of web application development in 2023.

Does TypeScript slow down development? ›

One of the primary issues with using Typescript is the slower compile time. This can be especially noticeable when working on a large codebase that needs to be compiled. The TypeScript compiler is not as efficient at optimizing code as other compilers, meaning that it takes longer to complete a compile task.

Will TS replace JS? ›

TypeScript is not a replacement for JavaScript. TypeScript is simply a more feature-full and technically sound way to write JavaScript. To run an application written in TypeScript, the first step is to compile the code into JavaScript.

What are the pros and cons of using TypeScript vs JavaScript? ›

TypeScript vs JavaScript comparison
TypeScript
Type systemStatic typing, strongly typed (optionally)
AdvantagesEasier to debug, quicker development
DisadvantagesMore initial setup, additional learning on top of JavaScript required
SupportEasily supports new features even on ES3 compatible browsers
5 more rows
Sep 29, 2020

Is it hard to learn TypeScript? ›

For many projects – especially medium to large projects – TypeScript will save you lots of time and headaches. And if you already know JavaScript, TypeScript won't be too hard to learn. It's a great tool to have in your arsenal.

Is TypeScript necessary for React reddit? ›

TypeScript everything and use varying levels of strictness depending on what it is for react projects. That way you get the best of both. For code you don't care about or can't be bothered to figure out the Types, just use liberal amounts of any and it's basically just JavaScript.

Is TypeScript easier than js? ›

JavaScript is interpreted, easier to learn, and the best choice for smaller projects. Meanwhile, TypeScript is compiled, harder to learn, and best used for complex and large-scale projects.

When should you not use react JS? ›

When you are making an app like a game or a demanding creative app, React is not the best choice. This problem stems from the fact that it uses a Virtual DOM. Virtual DOMs, or VDOMs, are layers that help make unoptimized DOM manipulations faster.

Is TypeScript more secure than JS? ›

While JavaScript is dynamically-typed, TypeScript is a statically-typed superset of JavaScript, which means it offers strict static typing as an option but will allow dynamic typing, as well. As a result, TypeScript code is safer but a little trickier to write, resulting in more errors earlier in development.

Is TypeScript better than Nodejs? ›

TypeScript was created with the aim of expanding the technical abilities of JavaScript. It offers static typing and helps discover the problems with coding prior to their appearance in the runtime environment. Node. js is an open-source development framework implemented for JavaScript execution on the server side.

How to convert React JS to React TypeScript? ›

Getting Started
  1. Run the React Project. Clone the repository. ...
  2. Adding TypeScript. In your terminal run npm install --save typescript @types/node @types/react @types/react-dom @types/websocket . ...
  3. Migrate React to TypeScript. Now that everything is up and running, we can start our migration.
Nov 26, 2022

Can I learn ReactJS in 2 days? ›

Like with any skill, you get better the more you practice. React has a good learning curve compared to other web development frameworks, so you shouldn't have any trouble picking up the fundamentals in a few days or weeks and mastering the language in a few months.

Can I learn react JS in 2 weeks? ›

ReactJS Basics

If you are a beginner or already have some programming experience, it will take you one to four weeks to completely master the basics.

Can I learn react JS in 10 days? ›

As with any skill, the more you practice, the better you get. React has a good learning curve in comparison to other web development frameworks, and so you should have no trouble learning the basics in a few days or weeks, and mastering the language in a few months.

What is the easiest way to learn TypeScript? ›

10 Best Online Courses to learn TypeScript in 2023
  1. Understanding TypeScript — 2023 Edition. ...
  2. Typescript: The Complete Developer's Guide [2023] — Udemy. ...
  3. Typescript Masterclass & FREE E-Book. ...
  4. TypeScript for Professionals [Udemy] ...
  5. TypeScript Fundamentals [Pluralsight Best Course] ...
  6. Introduction to TypeScript Development.

When should I start using TypeScript? ›

When it makes sense to use TypeScript
  1. When you have a large codebase. ...
  2. When your team's developers are already accustom to statically-typed languages. ...
  3. TypeScript can serve as a replacement for Babel. ...
  4. When a library or framework recommends TypeScript. ...
  5. When you really feel the need for speed.
Mar 24, 2016

Does TypeScript make JS faster? ›

Conclusion. In terms of both execution speed and device scaling, TypeScript is faster and more effective than JavaScript. Its ability to detect errors and bugs at the compilation stage rather than the runtime is the main reason it outperforms JavaScript in terms of performance.

Can I learn React in 4 days? ›

For a programmer who is already familiar with HTML and at least one other programming language, learning React will take no more than a single day. React may be learned by a novice programmer in a matter of days. There are more libraries and technologies that may be used with React, such as Redux or Relay.

Can I learn React in 30 days? ›

Learn React by building Applications

It is structured based on days and the challenge goes form day 1 to 30. In the 30 Days Of React challenge , you will have a chance to practice with small exercises, solve different challenging problems and build more than 30 simple and complex applications.

Can I learn ReactJS in 15 days? ›

I learnt React JS in 15 days. On my way, I had to learn JavaScript ES6 and Node JS. I also did a small project for practice. The conclusion I derived from these 15 days is that the fastest way to learn React JS is to practice it in a project.

Should I always use TypeScript instead of JavaScript? ›

TypeScript is better than JavaScript in terms of language features, reference validation, project scalability, collaboration within and between teams, developer experience, and code maintainability.

Should I always use TypeScript? ›

In terms of software development, TypeScript offers many advantages over JavaScript: Optional static typing. JavaScript is a dynamically typed language, which means that types are checked, and data type errors are only detected at runtime. This can be very dangerous and can create errors during production.

Why TypeScript is so much better than JavaScript? ›

Typescript allows for easier code restructuring when compared to JavaScript. This also makes identifying and fixing code errors in Typescript faster. At the time of development, TypeScript identifies the compilation bugs.

Why do people prefer TypeScript? ›

TypeScript extends JavaScript, providing a better developer experience. The benefits of using TypeScript over JavaScript include: Static typing – TypeScript comes with optional static typing and a type inference system, which means that a variable, declared with no type may be inferred by TypeScript based on its value.

Is TypeScript necessary for frontend? ›

Although TypeScript is more commonly used as a backend language, there is nothing stopping you from using it on the frontend. In fact, if you want to build a robust and scalable frontend, it is encouraged. As previously stated, anything built in JavaScript can be built in TypeScript.

What are alternatives to TypeScript for React? ›

In this article, we will continue our discussion and talk about the most popular TypeScript alternatives.
  • Opal. Opal https://opalrb.com/ is an open-source project that allows developers to write Ruby code that runs in the browser. ...
  • Kotlin/JS. ...
  • PureScript. ...
  • Scala. ...
  • ReScript. ...
  • ClojureScript. ...
  • Emscripten. ...
  • Fable.
Feb 20, 2023

Should I learn TypeScript first or next js? ›

You Know An Object-Oriented Programming Language

If you already know an OOP language like Java, C#, or Python, it might make sense to learn TypeScript first. It will allow you to get used to the JavaScript-like syntax while coding in a style that you are already accustomed to.

What is the best frontend for TypeScript? ›

Angular is a best frontend framework that is dominating the list of web frontend frameworks. It is a framework for creating efficient and advanced single-page applications. It is a Typescript-based development platform developed by Google.

Why should I switch to TypeScript? ›

TypeScript is a popular programming language that builds on JavaScript by adding types and type-checking. TypeScript can help you write more reliable, maintainable, and scalable code for your web applications.

Do people still use TypeScript? ›

According to Stack Overflow's 2021 Developer Survey, TypeScript is about as popular as PYPL indicates it is, coming in as the seventh most popular language, as ranked by approximately 83,000 developers.

Videos

1. Typescript for React Components From Beginners to Masters
(Jack Herrington)
2. TypeScript Course In ReactJS - TypeScript
(PedroTech)
3. React Typescript Tutorial with Project | Learn React JS with Typescript [2021]
(RoadsideCoder)
4. Converting React Apps to TypeScript - Josh Goldberg
(SitePen)
5. How to use TypeScript in React
(freeCodeCamp.org)
6. Add TypeScript to React in Less Than 5 Minutes
(Mattermost)

References

Top Articles
Latest Posts
Article information

Author: Carmelo Roob

Last Updated: 09/22/2023

Views: 6336

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.