React's Most Useful Types

Rate this content
Bookmark
The video covers key aspects of React's most useful types in TypeScript. It starts with an overview of JSX elements, highlighting the differences between React.jsx.element and React.ReactNode. The talk explains that React.FC, or React.FunctionComponent, is a utility type that ensures components return JSX and supports props and default props. React.FC vs JSX.Element is discussed, noting that React.FC used to return React.ReactElement but now returns ReactNode, allowing for more flexibility. The speaker emphasizes the stability and synchronization of React and Types React versions. The video also explores React.ComponentType, a type helper that represents any React component, whether class or function-based. React.ElementType is mentioned as useful for handling various types of inputs, including native tags. React.jsx.intrinsic elements provide a record of all possible DOM elements with their expected props, enhancing the developer experience. React.ComponentProps is another utility type for grabbing types from uncontrolled components. The talk also touches on React.ElementRef for obtaining the correct ref type for third-party components.

From Author:

We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.

In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?

You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.


This talk has been presented at React Day Berlin 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

Matt Pocock is a full-time TypeScript educator who provides resources and tutorials on TypeScript and React through his platform, tuttletypescript.com.

React does not include its own types by default to allow users the flexibility to install them separately via Types React, ensuring that users can opt for different type versions or setups.

The versioning of React and Types React is closely synced. For example, if React is at version 17, Types React will also be at version 17, and this alignment extends to major releases and patch changes.

React.jsx.element is used for JSX elements specifically, while React.ReactNode includes all possible types that can be rendered by a React component, such as strings, numbers, and JSX elements.

React.FC, or React.FunctionComponent, is a TypeScript utility type used to define functional components. It ensures the component returns JSX and supports props and default props.

React.jsx.intrinsic elements provide a record of all possible DOM elements with their expected props, allowing developers to easily access and extend these types when creating or manipulating elements in JSX.

React.componentType is a TypeScript utility type that can represent either a class component or a function component in React, allowing for more flexibility in assigning component types.

React.ElementType is useful for defining props for components that can accept various types of inputs, including native tags like 'input' or 'div', and ensuring that components are compatible with expected prop types.

React.elementRef is utilized to obtain the correct ref type for a given component, especially useful when dealing with third-party components where the ref type isn't explicitly known.

Matt Pocock
Matt Pocock
21 min
12 Dec, 2023

Comments

Sign in or register to post your comment.
  • Tewodros Birhanu
    Tewodros Birhanu
    self-employed
    Amazing Matt
  • Anuradha Kumari
    Anuradha Kumari
    VodafoneZiggo
    What an amazing talk, I learned a lot, Thanks Matt!

Video Transcription

Available in Español: Los tipos más útiles de React

1. React's Best Types and JSX

Short description:

Today I'm going to be talking about React's best types. React and Types React are actually one thing, united. The major version releases are all synced together. Types React is very, very stable. Types are part of your API and your framework. Let's start by talking about the type of JSX. It's a React.jsx.element or JSX.element.

What's up friends, my name is Matt Pocock. I'm a full-time TypeScript educator. I'm pretty gutted that I can't be in Berlin to actually see you guys and say hello and stuff, but stuff. That means I've got to be here in the UK, but you can find my stuff at tuttletypescript.com, go and support me, and, yeah, I'm excited to give this talk.

Today I'm going to be talking about React's best types. And you might think that's a kind of weird framing here, right? Because React itself doesn't ship its own types. It sort of just basically says, okay, you can install React here, and then, as a separate thing, we won't ship any types to you directly, but if you install Types React as well, then we're going to give you some types with it. And you might think, because of that, that the React team is sort of not really involved in the types. So you might think, sure, the community handles the Types React, and the React team handles React itself. But actually, it's more like this. It's more like the React team has stewardship over both of them. And actually, there are members of the React team that really just focus on the types and make sure that the types are correct. So you might think, sure, okay, the React and Types React, they're still separate things. But it's better to think of them as actually one thing, united. And that's because a lot of the decisions they make are synced together. The major version releases are all synced together. So if you have 17 on React, then Types React is also going to be 17, 18, etc. They also do ship patches. So Types React might ship a patch change without React shipping a change, but this means that they're really tied together. So Types React is very, very stable because really they consider any major change to the types to be something that React also needs a major version change for. So while React doesn't actually ship any types, it oversees its types very, very closely, and a lot of this is due to the really good work of Seb Silberman and a bunch of others. So it's important to think about the fact that types are features and types are part of your API. Types are part of your framework. And if you don't understand the types that come with React, you're not going to have a very good time using React with TypeScript. So this is my mission today is to teach you the most important types that React exposes and how you can use them to better power your apps and sort of just find your way around in React apps.

Let's start by talking about the type of JSX. If you have just a node up here, for instance, like this div, then what type does TypeScript infer this as? Well, if we hover over this node here, we can see that it's a React.jsx.element. You can also type this as just JSX.element. This is actually a relatively recent change. They've moved a lot of the global stuff that used to just be in JSX.element into a React namespace.

2. React JSX and React.reactnode

Short description:

So JSX.element represents a node of JSX, which can be a div with multiple div children. However, there are other things in React that can be rendered, such as strings, numbers, undefined, or null. These cannot be assigned to React.jsx.element, so the correct type to use is React.reactnode. React.reactnode represents all possible things that can be returned from a React component, including JSX, strings, numbers, and more.

So if you're using another project like solid or something in the same TypeScript TS config, it doesn't conflict. So JSX.element represents basically a node of JSX. It doesn't matter how many things are in that JSX node. So this could be a div with many other div children. It's always just React.jsx.element.

There's another type that goes along with this too, which is React.ReactElements, which is absolutely identical. In the React world, they both mean the same thing. And you might think that's really good. Now I understand every time I need to let's say type some children or something like that, I can use React.jsx.element and I'm all good to go. Except though, that there are lots of other things in React that you can render. It's not just like elements. You can render strings, you can render numbers, you can render undefined, or you can render null. All of these things are available to be returned from React components. And you can see by the number of errors here that these are basically not assignable to React.jsx.element. So you've probably seen at some point in your React career, type string is not assignable to type element or something along those lines. So in these situations, what is the correct type to use instead of React.jsx.element? Well, it's React.reactnode. React.reactnode, if we take a look at it, it contains string, number, boolean, React element, like a bunch of other stuff in here, React portal, null, or undefined. So it represents all of the possible things that you can return from a React component. This means if you need to type like a slot that can receive some JSX, like or a string or a number or anything that can be rendered to the DOM, then React.reactnode is the type that you need. Also 99% of the time, this is the type that you're going to want. I would actually just mostly ignore the fact that these types exist, React.jsx.element and basically just think of it as like, okay, we have some JSX here, what type does TypeScript need to give it? That's the type that it's gonna be. But in terms of actually using this, then actually like assigning types, actually using this within your application code, React.reactnode is the one that you are gonna need for using to represent JSX in all of its different forms.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

TypeScript and React: Secrets of a Happy Marriage
React Advanced Conference 2022React Advanced Conference 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
Designing APIs is a challenge, and it's important to consider the language used and different versions of the API. API ergonomics focus on ease of use and trade-offs. Routing is a misunderstood aspect of API design, and file-based routing can simplify it. Unplugging View Router provides typed routes and eliminates the need to pass routes when creating the router. Data loading and handling can be improved with data loaders and predictable routes. Handling protected routes and index and ID files are also discussed.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
This talk discusses the performance issues in TypeScript builds and introduces a new feature called isolated declarations. By running the compiler in parallel and using isolated modules, significant performance gains can be achieved. Isolated declarations improve build speed, compatibility with other tools, and require developers to write types in code. This feature has the potential to further increase performance and may be available in TypeScript soon.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Alex introduces tRPC, a toolkit for making end-to-end type-safe APIs easily, with auto-completion of API endpoints and inferred data from backend to frontend. tRPC works the same way in React Native and can be adopted incrementally. The example showcases backend communication with a database using queries and validators, with types inferred to the frontend and data retrieval done using Prisma ORM.
How to properly handle URL slug changes in Next.js
TypeScript Congress 2022TypeScript Congress 2022
10 min
How to properly handle URL slug changes in Next.js
Top Content
This Talk explains how to handle URL slug changes in Next.js by using the getStaticPaths and getStaticProps methods. It covers implementing redirects and provides a solution to eliminate the need for editors to perform additional steps. The approach involves tracking URL slug changes and issuing proper redirects. The speaker encourages the audience to reach out with any questions or experiences with handling URL slugs.

Workshops on related topic

React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side. 
Frictionless Development With Unified Type System
JSNation 2024JSNation 2024
113 min
Frictionless Development With Unified Type System
Featured Workshop
Ejiro Asiuwhu
Ejiro Asiuwhu
Imagine developing where frontend and backend sing in harmony, types dance in perfect sync, and errors become a distant memory. That's the magic of TypeScript Nirvana!
Join me on a journey to unveil the secrets of unified type definitions, the key to unlocking frictionless development. We'll dive into:
- Shared language, shared love: Define types once, share them everywhere. Consistency becomes your BFF, errors your worst nightmare (one you'll rarely see).- Effortless coding: Ditch the manual grind of type checking. TypeScript's got your back, freeing you to focus on building awesomeness.- Maintainability magic: With crystal-clear types guiding your code, maintaining it becomes a walk in the park. More time innovating, less time debugging.- Security fortress: TypeScript's type system shields your app from common vulnerabilities, making it a fortress against security threats.