Home Web Front-end JS Tutorial How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Oct 30, 2024 am 06:59 AM

Let's start with a scenario and a task associated with it.

We have a messaging application with a status bar that shows the user's current status and allows them to update it. We have to add a dropdown from which the user can change their status and use useState() to show and update the user's current status in the UI.

For simplicity, we will only focus on the useState implementation in this article, and by the end of the article, you will understand how even for a simple example TypeScript is a much more powerful option.

The Task

We have to define a useState() that stores and updates userStatus and is initialized with one of the five possible status options (let's say active).

All the possible options are:

  1. Active (active)
  2. Away (away)
  3. Do Not Disturb (dnd)
  4. On Leave (leave)
  5. Out Of Office (OOO)

JSX/JS

This is a very straightforward task, right? All we have to do is define a useState and initialize it to active and then use the set function to update the status and we are done.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

But wait! What happens when someone is reviewing my code or visits this piece of code later (say after 1 week, 2 weeks, 1 month, 6 months, or whatever), how will they know what are all the possible/valid options?

Ahh! Yes, we can add a comment next to the useState to let them know that these are all the possible options.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

But, this isn't a good solution, right? So, how can we improve it?

Object Lookup

Object lookup is a really nice solution to our problem. So, let's start with defining an object lookup called UserStatus and use it to set our userStatus value.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Now, let's update our useState definition.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Now, let's try to update the status.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Ohh! Look at that, now we get autocomplete in our editor and can check all the possible/valid values of userStatus by looking at the definition of UserStatus.

The Issues with Object Lookup

Even though the object lookup method has seemingly solved our problem and is definitely a far better solution than just adding comments, it still has two major issues:

  1. For anyone visiting our piece of code later, they have to know that we are using an object lookup to set our state. This might seem trivial but imagine as our component grows and becomes more complex, then it becomes very easy for someone to be unaware of our implementation.
  2. It still doesn't prevent anyone from setting any random value to our state, even when they are aware of the object lookup.  

So, how can we solve these issues?
Answer: Typescript

TSX/TS

Let's start again with our solution, but this time in a .tsx or a Typescript file. We can start by defining a useState() function and initializing it with the value: active.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Nothing seems different right now, but it is. Let's update the userStatus value.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Ahh! As you can see it is giving us that dreaded red squiggly error line around some set functions but not on ones where we are setting a string value. This is because Typescript is inferring the type of our state from its initial value (i.e. type string).

Yes, this will prevent us from setting any non-string values to our userStatus state, but it still doesn't prevent us from setting any random string value and we still have to use the object lookup for documenting all the possible options, you may ask.
 

Let's do some "One Stone, Two Birds".

Explicit Types and Generics

In Typescript we can create custom types and it also has support for generics which can be used in React for its hook definitions, in our case the useState() hook.

Let's create a new UserStatus type in our React component.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Now, let's use this type in our useState definition.

How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Till now, everything looks similar to how we were doing it in the object lookup method, but the magic of Typescript is when we start using our set function and the state value.

  1. Getting the type definition of userStatus.
    How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

  2. Autocomplete for the setUserStatus function.
    How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

  3. Getting proper validation for valid and invalid values.
    How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example)

Look at that,

  1. We can get the documentation of all the valid values by simply hovering over the userStatus and looking up its type definition.
  2. However, we don't need to look at the type definition of our state value when using the set function, as it automatically gives us the autocomplete for all the valid options.
  3. Now it not only gives us the error when setting a non-string value, but it also gives us the error for using invalid string values (i.e. it will always give errors for invalid inputs).

Conclusion

By now, you probably have got a good feel for how TypeScript can really enhance our development experience. We have only scratched the surface with a simple example here, but just think about the real-world applications we’re building, using TypeScript could mean way fewer bugs and a way better developer experience overall.

I hope this article encourages you to start using Typescript in all your React applications and build awesome web experiences.

If you liked this article and would like to connect, then you can connect with me on Linked and X/Twitter

The above is the detailed content of How TypeScript Makes React Better: Smoother Developer Experience, Fewer Bugs (With a useState Example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles