React's Most Useful Types

Rate this content
Bookmark

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.


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 Summary and Transcription

Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.

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
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
Type-checking a TypeScript codebase can be slow, especially for monorepos containing lots of projects that each need to use the type checker to generate type declaration files. In this talk, we introduce — for the very first time — a new TypeScript feature we are working on called “Isolated Declarations” that allows DTS files to be generated without using the type checker at all! This opens the door to faster declaration generation in TypeScript itself, as well as in external tools written in other languages such as ESBuild and swc. You'll see how to use this new option, and maybe (just maybe) you’ll be convinced about the benefits of explicit return types! Most importantly, we will show how Isolated Declarations enables parallel builds to spread work across your CPU cores to significantly improve the build speed of your TypeScript projects.
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
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.
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
If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.

Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 

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.
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.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
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.
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
 
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
 
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
 
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
Advanced TypeScript types for fun and reliability
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
Maurice de Beijer
Maurice de Beijer
If you're looking to get the most out of TypeScript, this workshop is for you! In this interactive workshop, we will explore the use of advanced types to improve the safety and predictability of your TypeScript code. You will learn when to use types like unknown or never. We will explore the use of type predicates, guards and exhaustive checking to make your TypeScript code more reliable both at compile and run-time. 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.
Are you familiar with the basics of TypeScript and want to dive deeper? Then please join me with your laptop in this advanced and interactive workshop to learn all these topics and more.
You can find the slides, with links, here: http://theproblemsolver.nl/docs/ts-advanced-workshop.pdf
And the repository we will be using is here: https://github.com/mauricedb/ts-advanced
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.