React+TypeScript Cheatsheets

react + ts logo

Cheatsheets for experienced React developers getting started with TypeScript

[**Web docs**](https://react-typescript-cheatsheet.netlify.app/docs/basic/setup) | [中文翻译](https://github.com/fi3ework/blog/tree/master/react-typescript-cheatsheet-cn) | [**Español**](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet-es) | [**Português**](https://github.com/typescript-cheatsheets/react-pt) | [Contribute!](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/blob/master/CONTRIBUTING.md) | [Ask!](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new/choose)
---
:wave: This repo is maintained by [@swyx](https://twitter.com/swyx), [@ferdaber](https://twitter.com/ferdaber), [@eps1lon](https://twitter.com/sebsilbermann), [@jsjoeio](https://twitter.com/jsjoeio) and [@arvindcheenu](https://twitter.com/arvincheenu), we're so happy you want to try out TypeScript with React! If you see anything wrong or missing, please [file an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new/choose)! :+1:
--- [![All Contributors](https://img.shields.io/github/contributors/typescript-cheatsheets/react-typescript-cheatsheet?color=orange&style=flat-square)](/CONTRIBUTORS.md) | [![Discord](https://img.shields.io/discord/508357248330760243.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/wTGS5z9) | [![Tweet](https://img.shields.io/twitter/url?label=Help%20spread%20the%20word%21&style=social&url=https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact)](http://twitter.com/home?status=Awesome%20%40Reactjs%20%2B%20%40TypeScript%20cheatsheet%20by%20%40ferdaber%2C%20%40sebsilbermann%2C%20%40swyx%20%26%20others!%20https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact) ## All React + TypeScript Cheatsheets - **The Basic Cheatsheet** ([`/README.md`](/README.md#basic-cheatsheet-table-of-contents)) is focused on helping React devs just start using TS in React **apps** - Focus on opinionated best practices, copy+pastable examples. - Explains some basic TS types usage and setup along the way. - Answers the most Frequently Asked Questions. - Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies. - The goal is to get effective with TS without learning _too much_ TS. - **The Advanced Cheatsheet** ([`/ADVANCED.md`](https://react-typescript-cheatsheet.netlify.app/docs/advanced/intro)) helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React **libraries**. - It also has miscellaneous tips and tricks for pro users. - Advice for contributing to DefinitelyTyped. - The goal is to take _full advantage_ of TypeScript. - **The Migrating Cheatsheet** ([`/MIGRATING.md`](https://react-typescript-cheatsheet.netlify.app/docs/migration/intro)) helps collate advice for incrementally migrating large codebases from JS or Flow, **from people who have done it**. - We do not try to convince people to switch, only to help people who have already decided. - ⚠️This is a new cheatsheet, all assistance is welcome. - **The HOC Cheatsheet** ([`/HOC.md`](https://react-typescript-cheatsheet.netlify.app/docs/hoc/intro)) specifically teaches people to write HOCs with examples. - Familiarity with [Generics](https://www.typescriptlang.org/docs/handbook/generics.html) is necessary. - ⚠️This is the newest cheatsheet, all assistance is welcome. --- ### Basic Cheatsheet Table of Contents
Expand Table of Contents - [Section 1: Setup TypeScript with React](#section-1-setup-typescript-with-react) - [Prerequisites](#prerequisites) - [React + TypeScript Starter Kits](#react--typescript-starter-kits) - [Import React](#import-react) - [Section 2: Getting Started](#section-2-getting-started) - [Function Components](#function-components) - [Hooks](#hooks) - [useState](#usestate) - [useReducer](#usereducer) - [useEffect](#useeffect) - [useRef](#useref) - [useImperativeHandle](#useimperativehandle) - [Custom Hooks](#custom-hooks) - [Class Components](#class-components) - [You May Not Need `defaultProps`](#you-may-not-need-defaultprops) - [Typing `defaultProps`](#typing-defaultprops) - [Consuming Props of a Component with defaultProps](#consuming-props-of-a-component-with-defaultprops) - [Problem Statement](#problem-statement) - [Solution](#solution) - [Misc Discussions and Knowledge](#misc-discussions-and-knowledge) - [Basic Prop Types Examples](#basic-prop-types-examples) - [Useful React Prop Type Examples](#useful-react-prop-type-examples) - [getDerivedStateFromProps](#getderivedstatefromprops) - [Forms and Events](#forms-and-events) - [Context](#context) - [Basic Example](#basic-example) - [Extended Example](#extended-example) - [forwardRef/createRef](#forwardrefcreateref) - [Portals](#portals) - [Error Boundaries](#error-boundaries) - [Option 1: Using react-error-boundary](#option-1-using-react-error-boundary) - [Options 2: Writing your custom error boundary component](#options-2-writing-your-custom-error-boundary-component) - [Concurrent React/React Suspense](#concurrent-reactreact-suspense) - [Troubleshooting Handbook: Types](#troubleshooting-handbook-types) - [Union Types and Type Guarding](#union-types-and-type-guarding) - [Optional Types](#optional-types) - [Enum Types](#enum-types) - [Type Assertion](#type-assertion) - [Simulating Nominal Types](#simulating-nominal-types) - [Intersection Types](#intersection-types) - [Union Types](#union-types) - [Overloading Function Types](#overloading-function-types) - [Using Inferred Types](#using-inferred-types) - [Using Partial Types](#using-partial-types) - [The Types I need weren't exported!](#the-types-i-need-werent-exported) - [The Types I need don't exist!](#the-types-i-need-dont-exist) - [Slapping `any` on everything](#slapping-any-on-everything) - [Autogenerate types](#autogenerate-types) - [Typing Exported Hooks](#typing-exported-hooks) - [Typing Exported Components](#typing-exported-components) - [Troubleshooting Handbook: Operators](#troubleshooting-handbook-operators) - [Troubleshooting Handbook: Utilities](#troubleshooting-handbook-utilities) - [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook-tsconfigjson) - [Troubleshooting Handbook: Fixing bugs in official typings](#troubleshooting-handbook-fixing-bugs-in-official-typings) - [Troubleshooting Handbook: Globals, Images and other non-TS files](#troubleshooting-handbook-globals-images-and-other-non-ts-files) - [Other React + TypeScript resources](#other-react--typescript-resources) - [Editor Tooling and Integration](#editor-tooling-and-integration) - [Linting](#linting) - [Other React + TypeScript resources](#other-react--typescript-resources-1) - [Recommended React + TypeScript talks](#recommended-react--typescript-talks) - [Time to Really Learn TypeScript](#time-to-really-learn-typescript) - [Example App](#example-app) - [My question isn't answered here!](#my-question-isnt-answered-here) - [Contributors](#contributors) - [Prerequisites](#prerequisites) - [React + TypeScript Starter Kits](#react--typescript-starter-kits) - [Import React](#import-react) - [Section 2: Getting Started](#section-2-getting-started) - [Function Components](#function-components) - [Hooks](#hooks) - [Class Components](#class-components) - [Typing defaultProps](#typing-defaultprops) - [Types or Interfaces?](#types-or-interfaces) - [Basic Prop Types Examples](#basic-prop-types-examples) - [Useful React Prop Type Examples](#useful-react-prop-type-examples) - [getDerivedStateFromProps](#getDerivedStateFromProps) - [Forms and Events](#forms-and-events) - [Context](#context) - [forwardRef/createRef](#forwardrefcreateref) - [Portals](#portals) - [Error Boundaries](#error-boundaries) - [Concurrent React/React Suspense](#concurrent-reactreact-suspense) - [Basic Troubleshooting Handbook: Types](#basic-troubleshooting-handbook-types) - [Union Types and Type Guarding](#union-types-and-type-guarding) - [Optional Types](#optional-types) - [Enum Types](#enum-types) - [Type Assertion](#type-assertion) - [Simulating Nominal Types](#simulating-nominal-types) - [Intersection Types](#intersection-types) - [Union Types](#union-types) - [Overloading Function Types](#overloading-function-types) - [Using Inferred Types](#using-inferred-types) - [Using Partial Types](#using-partial-types) - [The Types I need weren't exported!](#the-types-i-need-werent-exported) - [The Types I need don't exist!](#the-types-i-need-dont-exist) - [Slapping `any` on everything](#slapping-any-on-everything) - [Autogenerate types](#autogenerate-types) - [Typing Exported Hooks](#typing-exported-hooks) - [Typing Exported Components](#typing-exported-components) - [Troubleshooting Handbook: Operators](#troubleshooting-handbook-operators) - [Troubleshooting Handbook: Utilties](#troubleshooting-handbook-utilities) - [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook-tsconfigjson) - [Troubleshooting Handbook: Bugs in official typings](#troubleshooting-handbook-bugs-in-official-typings) - [Recommended React + TypeScript codebases to learn from](#recommended-react--typescript-codebases-to-learn-from) - [Editor Tooling and Integration](#editor-tooling-and-integration) - [Linting](#linting) - [Other React + TypeScript resources](#other-react--typescript-resources) - [Recommended React + TypeScript talks](#recommended-react--typescript-talks) - [Time to Really Learn TypeScript](#time-to-really-learn-typescript) - [Example App](#example-app) - [My question isn't answered here!](#my-question-isnt-answered-here)
# Section 1: Setup TypeScript with React ## Prerequisites 1. good understanding of [React](https://reactjs.org) 2. familiarity with [TypeScript Types](https://www.typescriptlang.org/docs/handbook/basic-types.html) ([2ality's guide](http://2ality.com/2018/04/type-notation-typescript.html) is helpful. If you’re an absolute beginner in TypeScript, check out [chibicode’s tutorial](https://ts.chibicode.com/todo/).) 3. having read [the TypeScript section in the official React docs](https://reactjs.org/docs/static-type-checking.html#typescript). 4. having read [the React section of the new TypeScript playground](http://www.typescriptlang.org/play/index.html?jsx=2&esModuleInterop=true&e=181#example/typescript-with-react) (optional: also step through the 40+ examples under [the playground's](http://www.typescriptlang.org/play/index.html) Examples section) This guide will always assume you are starting with the latest TypeScript version. Notes for older versions will be in expandable `
` tags. ## React + TypeScript Starter Kits Cloud setups: - [TypeScript Playground with React](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwCwAUKJLHAN5wCuqWAyjMhhYANFx4BRAgSz44AXzhES5Snhi1GjLAA8W8XBAB2qeAGEInQ0KjjtycABsscALxwAFAEpXAPnaM4OANjeABtA0sYUR4Yc0iAXVcxPgEhdwAGT3oGAOTJaXx3L19-BkDAgBMIXE4QLCsAOhhgGCckgAMATQsgh2BcAGssCrgAEjYIqwVmutR27MC5LM0yuEoYTihDD1zAgB4K4AA3H13yvbAfbs5e-qGRiYspuBmsVD2Aekuz-YAjThgMCMcCMpj6gxcbGKLj8MTiVnck3gAGo4ABGTxyU6rcrlMF3OB1H5wT7-QFGbG4z6HE65ZYMOSMIA) just if you are debugging types (and reporting issues), not for running code - [CodeSandbox](http://ts.react.new) - cloud IDE, boots up super fast - [Stackblitz](https://stackblitz.com/edit/react-typescript-base) - cloud IDE, boots up super fast Local dev setups: - [Next.js](https://nextjs.org/docs/basic-features/typescript): `npx create-next-app -e with-typescript` will create in your current folder - [Create React App](https://facebook.github.io/create-react-app/docs/adding-typescript): `npx create-react-app name-of-app --template typescript` will create in new folder - [Meteor](https://guide.meteor.com/build-tool.html#typescript): `meteor create --typescript name-of-my-new-typescript-app` - [Ignite](https://github.com/infinitered/ignite#use-ignite-andross-infinite-red-andross-boilerplate) for React Native: `ignite new myapp` - [TSDX](https://tsdx.io/): `npx tsdx create mylib` for Creating React+TS _libraries_. (in future: [TurboRepo](https://twitter.com/jaredpalmer/status/1346217789942591488))
Other tools Less mature tools still worth checking out: - [Vite](https://twitter.com/swyx/status/1282727239230996480?lang=en): `npm init vite-app my-react-project --template react-ts` (note - not yet v1.0, but very fast) - [Snowpack](): `npx create-snowpack-app my-app --template app-template-react-typescript` - [Docusaurus v2](https://v2.docusaurus.io/docs/installation) with [TypeScript Support](https://v2.docusaurus.io/docs/typescript-support) - [Parcel](https://v2.parceljs.org/languages/typescript/) - [JP Morgan's `modular`](https://github.com/jpmorganchase/modular): CRA + TS + Yarn Workspaces toolkit. `yarn create modular-react-app ` Manual setup: - [Basarat's guide](https://github.com/basarat/typescript-react/tree/master/01%20bootstrap) for **manual setup** of React + TypeScript + Webpack + Babel - In particular, make sure that you have `@types/react` and `@types/react-dom` installed ([Read more about the DefinitelyTyped project if you are unfamiliar](https://definitelytyped.org/)) - There are also many React + TypeScript boilerplates, please see [our Other Resources list](https://react-typescript-cheatsheet.netlify.app/docs/basic/recommended/resources/).
## Import React ```tsx import * as React from "react"; import * as ReactDOM from "react-dom"; ``` This is the [most futureproof way](https://www.reddit.com/r/reactjs/comments/iyehol/import_react_from_react_will_go_away_in_distant/) to import React. If you set `--allowSyntheticDefaultImports` (or add `"allowSyntheticDefaultImports": true`) in your `tsconfig.json` you can use more familiar imports: ```tsx import React from "react"; import ReactDOM from "react-dom"; ```
Explanation Why `allowSyntheticDefaultImports` over `esModuleInterop`? [Daniel Rosenwasser](https://twitter.com/drosenwasser/status/1003097042653073408) has said that it's better for webpack/parcel. For more discussion check out You should also check [the new TypeScript docs for official descriptions between each compiler flag](https://www.typescriptlang.org/tsconfig#allowSyntheticDefaultImports)!
# Section 2: Getting Started ## Function Components These can be written as normal functions that take a `props` argument and return a JSX element. ```tsx type AppProps = { message: string }; /* could also use interface */ const App = ({ message }: AppProps) =>
{message}
; ```
Why is `React.FC` discouraged? What about `React.FunctionComponent`/`React.VoidFunctionComponent`? You may see this in many React+TypeScript codebases: ```tsx const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
{message}
); ``` However, the general consensus today is that `React.FunctionComponent` (or the shorthand `React.FC`) is [discouraged](https://github.com/facebook/create-react-app/pull/8177). This is a nuanced opinion of course, but if you agree and want to remove `React.FC` from your codebase, you can use [this jscodeshift codemod](https://github.com/gndelia/codemod-replace-react-fc-typescript). Some differences from the "normal function" version: - `React.FunctionComponent` is explicit about the return type, while the normal function version is implicit (or else needs additional annotation). - It provides typechecking and autocomplete for static properties like `displayName`, `propTypes`, and `defaultProps`. - Note that there are some known issues using `defaultProps` with `React.FunctionComponent`. See [this issue for details](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/87). We maintain a separate `defaultProps` section you can also look up. - It provides an implicit definition of `children` (see below) - however there are some issues with the implicit `children` type (e.g. [DefinitelyTyped#33006](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/33006)), and it might be better to be explicit about components that consume `children`, anyway. ```tsx const Title: React.FunctionComponent<{ title: string }> = ({ children, title, }) =>
{children}
; ```
Using `React.VoidFunctionComponent` or `React.VFC` instead As of [@types/react 16.9.48](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643), you can also use `React.VoidFunctionComponent` or `React.VFC` type if you want to type `children` explicitly. This is an interim solution until `FunctionComponent` will accept no children by default (planned for `@types/react@^18.0.0`). ```ts type Props = { foo: string }; // OK now, in future, error const FunctionComponent: React.FunctionComponent = ({ foo, children, }: Props) => { return (
{foo} {children}
); // OK }; // Error now, in future, deprecated const VoidFunctionComponent: React.VoidFunctionComponent = ({ foo, children, }) => { return (
{foo} {children}
); }; ```
- _In the future_, it may automatically mark props as `readonly`, though that's a moot point if the props object is destructured in the parameter list. In most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of `React.FunctionComponent`.
Minor Pitfalls These patterns are not supported: **Conditional rendering** ```tsx const MyConditionalComponent = ({ shouldRender = false }) => shouldRender ?
: false; // don't do this in JS either const el = ; // throws an error ``` This is because due to limitations in the compiler, function components cannot return anything other than a JSX expression or `null`, otherwise it complains with a cryptic error message saying that the other type is not assignable to `Element`. ```tsx const MyArrayComponent = () => Array(5).fill(
); const el2 = ; // throws an error ``` **Array.fill** Unfortunately just annotating the function type will not help so if you really need to return other exotic types that React supports, you'd need to perform a type assertion: ```tsx const MyArrayComponent = () => (Array(5).fill(
) as any) as JSX.Element; ``` [See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/57).
## Hooks Hooks are [supported in `@types/react` from v16.8 up](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031). ## useState Type inference works very well most of the time: ```tsx const [val, toggle] = React.useState(false); // `val` is inferred to be a boolean // `toggle` only takes booleans ``` See also the [Using Inferred Types](https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#using-inferred-types) section if you need to use a complex type that you've relied on inference for. However, many hooks are initialized with null-ish default values, and you may wonder how to provide types. Explicitly declare the type, and use a union type: ```tsx const [user, setUser] = React.useState(null); // later... setUser(newUser); ``` ## useReducer You can use [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions) for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it. ```tsx const initialState = { count: 0 }; type ACTIONTYPE = | { type: "increment"; payload: number } | { type: "decrement"; payload: string }; function reducer(state: typeof initialState, action: ACTIONTYPE) { switch (action.type) { case "increment": return { count: state.count + action.payload }; case "decrement": return { count: state.count - Number(action.payload) }; default: throw new Error(); } } function Counter() { const [state, dispatch] = React.useReducer(reducer, initialState); return ( <> Count: {state.count} ); } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA)
Usage with `Reducer` from `redux` In case you use the [redux](https://github.com/reduxjs/redux) library to write reducer function, It provides a convenient helper of the format `Reducer` which takes care of the return type for you. So the above reducer example becomes: ```tsx import { Reducer } from 'redux'; export function reducer: Reducer() {} ```
## useEffect When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions: ```ts function DelayedEffect(props: { timerMs: number }) { const { timerMs } = props; useEffect( () => setTimeout(() => { /* do stuff */ }, timerMs), [timerMs] ); // bad example! setTimeout implicitly returns a number // because the arrow function body isn't wrapped in curly braces return null; } ```
Solution to the above example ```tsx function DelayedEffect(props: { timerMs: number }) { const { timerMs } = props; useEffect(() => { setTimeout(() => { /* do stuff */ }, timerMs); }, [timerMs]); // better; use the void keyword to make sure you return undefined return null; } ```
## useRef When using `useRef`, you have two options when creating a ref container that does not have an initial value: ```ts const ref1 = useRef(null!); const ref2 = useRef(null); ``` The first option will make `ref1.current` read-only, and is intended to be passed in to built-in `ref` attributes that React will manage (because React handles setting the `current` value for you).
What is the ! at the end of null!? `null!` is a non-null assertion operator (the `!`). It asserts that any expression before it is not `null` or `undefined`, so if you have `useRef(null!)` it means that you're instantiating the ref with a current value of `null` but lying to TypeScript that it's not `null`. ```ts function MyComponent() { const ref1 = useRef(null!); useEffect(() => { doSomethingWith(ref1.current); // TypeScript won't require null-check e.g. ref1 && ref1.current }); return
etc
; } ```
The second option will make `ref2.current` mutable, and is intended for "instance variables" that you manage yourself. ```tsx function TextInputWithFocusButton() { // initialise with null, but tell TypeScript we are looking for an HTMLInputElement const inputEl = React.useRef(null); const onButtonClick = () => { // strict null checks need us to check if inputEl and current exist. // but once current exists, it is of type HTMLInputElement, thus it // has the method focus! ✅ if (inputEl && inputEl.current) { inputEl.current.focus(); } }; return ( <> {/* in addition, inputEl only can be used with input elements. Yay! */} ); } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wFgAoCzAVwDsNgJa4AVJADxgElaxqYA6sBgALAGIQ01AM4AhfjCYAKAJRwA3hThwA9DrjBaw4CgA2waUjgB3YSLi1qp0wBo4AI35wYSZ6wCeYEgAymhQwGDw1lYoRHCmEBAA1oYA5nCY0HAozAASLACyADI8fDAAoqZIIEi0MFpwaEzS8IZllXAAvIjEMAB0MkjImAA8+cWl-JXVtTAAfEqOzioA3A1NtC1wTPIwirQAwuZoSV1wql1zGg3aenAt4RgOTqaNIkgn0g5ISAAmcDJvBA3h9TsBMAZeFNXjl-lIoEQ6nAOBZ+jddPpPPAmGgrPDEfAUS1pG5hAYvhAITBAlZxiUoRUqjU6m5RIDhOi7iIUF9RFYaqIIP9MlJpABCOCAUHJ0eDzm1oXAAGSKyHtUx9fGzNSacjaPWq6Ea6gI2Z9EUyVRrXV6gC+DRtVu0RBgxuYSnRIzm6O06h0ACpIdlfr9jExSQyOkxTP5GjkPFZBv9bKIDYSmbNpH04ABNFD+CV+nR2636kby+BETCddTlyo27w0zr4HycfC6L0lvUjLH7baHY5Jas7BRMI7AE42uYSUXed6pkY6HtMDulnQruCrCg2oA) example from [Stefan Baumgartner](https://fettblog.eu/typescript-react/hooks/#useref) ## useImperativeHandle _we dont have much here, but this is from [a discussion in our issues](https://github.com/typescript-cheatsheets/react/issues/106). Please contribute if you have anything to add!_ ```tsx type ListProps = { items: ItemType[]; innerRef?: React.Ref<{ scrollToItem(item: ItemType): void }>; }; function List(props: ListProps) { useImperativeHandle(props.innerRef, () => ({ scrollToItem() {}, })); return null; } ``` ## Custom Hooks If you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, use [TS 3.4 const assertions](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions): ```tsx export function useLoading() { const [isLoading, setState] = React.useState(false); const load = (aPromise: Promise) => { setState(true); return aPromise.finally(() => setState(false)); }; return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[] } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?target=5&jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA) This way, when you destructure you actually get the right types based on destructure position.
Alternative: Asserting a tuple return type If you are [having trouble with const assertions](https://github.com/babel/babel/issues/9800), you can also assert or define the function return types: ```tsx export function useLoading() { const [isLoading, setState] = React.useState(false); const load = (aPromise: Promise) => { setState(true); return aPromise.finally(() => setState(false)); }; return [isLoading, load] as [ boolean, (aPromise: Promise) => Promise ]; } ``` A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks: ```tsx function tuplify(...elements: T) { return elements; } function useArray() { const numberValue = useRef(3).current; const functionValue = useRef(() => {}).current; return [numberValue, functionValue]; // type is (number | (() => void))[] } function useTuple() { const numberValue = useRef(3).current; const functionValue = useRef(() => {}).current; return tuplify(numberValue, functionValue); // type is [number, () => void] } ```
Note that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however. ## More Hooks + TypeScript reading: - https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d - https://fettblog.eu/typescript-react/hooks/#useref If you are writing a React Hooks library, don't forget that you should also expose your types for users to use. ## Example React Hooks + TypeScript Libraries: - https://github.com/mweststrate/use-st8 - https://github.com/palmerhq/the-platform - https://github.com/sw-yx/hooks [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## Class Components Within TypeScript, `React.Component` is a generic type (aka `React.Component`), so you want to provide it with (optional) prop and state type parameters: ```tsx type MyProps = { // using `interface` is also ok message: string; }; type MyState = { count: number; // like this }; class App extends React.Component { state: MyState = { // optional second annotation for better type inference count: 0, }; render() { return (
{this.props.message} {this.state.count}
); } } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgFlqAFHMAZzgF44BvCuHAD0QuAFd2wAHYBzOAANpMJFEzok8uME4oANuwhwIAawFwQSduxQykALjjsYUaTIDcFAL4fyNOo2oAZRgUZW4+MzQIMSkYBykxEAAjFTdhUV1gY3oYAAttLx80XRQrOABBMDA4JAAPZSkAE05kdBgAOgBhXEgpJFiAHiZWCA4AGgDg0KQAPgjyQSdphyYpsJ5+BcF0ozAYYAgpPUckKKa4FCkpCBD9w7hMaDgUmGUoOD96aUwVfrQkMyCKIxOJwAAMZm8ZiITRUAAoAJTzbZwIgwMRQKRwOGA7YDRrAABuM1xKN4eW07TAbHY7QsVhsSE8fAptKWynawNinlJcAGQgJxNxCJ8gh55E8QA) Don't forget that you can export/import/extend these types/interfaces for reuse.
Why annotate state twice? It isn't strictly necessary to annotate the `state` class property, but it allows better type inference when accessing `this.state` and also initializing the state. This is because they work in two different ways, the 2nd generic type parameter will allow `this.setState()` to work correctly, because that method comes from the base class, but initializing `state` inside the component overrides the base implementation so you have to make sure that you tell the compiler that you're not actually doing anything different. [See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/57).
No need for readonly You often see sample code include `readonly` to mark props and state immutable: ```tsx type MyProps = { readonly message: string; }; type MyState = { readonly count: number; }; ``` This is not necessary as `React.Component` already marks them as immutable. ([See PR and discussion!](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813))
**Class Methods**: Do it like normal, but just remember any arguments for your functions also need to be typed: ```tsx class App extends React.Component<{ message: string }, { count: number }> { state = { count: 0 }; render() { return (
this.increment(1)}> {this.props.message} {this.state.count}
); } increment = (amt: number) => { // like this this.setState((state) => ({ count: state.count + amt, })); }; } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN5wQSBigDmSAFxw6MKMB5q4AXwA0cRWggBXHjG09rIAEZIoJgHwWKcHTBTccAC8FnBWtvZwAAwmANw+cET8bgAUAJTe5L6+RDDWUDxwKQnZcLJ8wABucBA8YtTAaADWQfLpwV4wABbAdCIGaETKdikAjGnGHiWlFt29ImA4YH3KqhrGsz19ugFIIuF2xtO+sgD0FZVTWdlp8ddH1wNDMsFFKCCRji5uGUFe8tNTqc4A0mkg4HM6NNISI6EgYABlfzcFI7QJ-IoA66lA6RNF7XFwADUcHeMGmxjStwSxjuxiAA) **Class Properties**: If you need to declare class properties for later use, just declare it like `state`, but without assignment: ```tsx class App extends React.Component<{ message: string; }> { pointer: number; // like this componentDidMount() { this.pointer = 3; } render() { return (
{this.props.message} and {this.pointer}
); } } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN4U4cEEgYoA5kgBccOjCjAeGgNwUAvgD44i8sshHuUXTwCuIAEZIoJuAHo-OGpgAGskOBgAC2A6JTg0SQhpHhgAEWA+AFkIVxSACgBKGzjlKJiRBxTvOABeOABmMzs4cziifm9C4ublIhhXKB44PJLlOFk+YAA3S1GxmzK6CpwwJdV1LXM4FH4F6KXKp1aesdk-SZnRgqblY-MgA) [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## Typing getDerivedStateFromProps Before you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be implemented using hooks which can also help set up memoization. Here are a few ways in which you can annotate `getDerivedStateFromProps` 1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it. ```tsx class Comp extends React.Component { static getDerivedStateFromProps( props: Props, state: State ): Partial | null { // } } ``` 2. When you want the function's return value to determine your state. ```tsx class Comp extends React.Component< Props, ReturnType > { static getDerivedStateFromProps(props: Props) {} } ``` 3. When you want derived state with other state fields and memoization ```tsx type CustomValue = any; interface Props { propA: CustomValue; } interface DefinedState { otherStateField: string; } type State = DefinedState & ReturnType; function transformPropsToState(props: Props) { return { savedPropA: props.propA, // save for memoization derivedState: props.propA, }; } class Comp extends React.PureComponent { constructor(props: Props) { super(props); this.state = { otherStateField: "123", ...transformPropsToState(props), }; } static getDerivedStateFromProps(props: Props, state: State) { if (isEqual(props.propA, state.savedPropA)) return null; return transformPropsToState(props); } } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA) ## You May Not Need `defaultProps` As per [this tweet](https://twitter.com/dan_abramov/status/1133878326358171650), defaultProps will eventually be deprecated. You can check the discussions here: - https://twitter.com/hswolff/status/1133759319571345408 The consensus is to use object default values. Function Components: ```tsx type GreetProps = { age?: number }; const Greet = ({ age = 21 }: GreetProps) => // etc ``` Class Components: ```tsx type GreetProps = { age?: number; }; class Greet extends React.Component { render() { const { age = 21 } = this.props; /*...*/ } } let el = ; ``` ## Typing `defaultProps` Type inference improved greatly for `defaultProps` in [TypeScript 3.0+](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html), although [some edge cases are still problematic](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/61). **Function Components** ```tsx type GreetProps = { age: number } & typeof defaultProps; const defaultProps = { age: 21, }; const Greet = (props: GreetProps) => { // etc }; Greet.defaultProps = defaultProps; ``` _[See this in TS Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAOKVYwAKxY6ALxwA3igDmWAFxwAdgFcQAIyxQ4AXzgAyOM1YQCcACZYCyeQBte-VPVwRZqeCbOXrEAXGEi6cCdLgAJgBGABo6dXo6e0d4TixuLzgACjAbGXjuPg9UAEovAD5RXzhKGHkoWTgAHiNgADcCkTScgDpkSTgAeiQFZVVELvVqrrrGiPpMmFaXcytsz2FZtwXbOiA)_ For **Class components**, there are [a couple ways to do it](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/pull/103#issuecomment-481061483)(including using the `Pick` utility type) but the recommendation is to "reverse" the props definition: ```tsx type GreetProps = typeof Greet.defaultProps & { age: number; }; class Greet extends React.Component { static defaultProps = { age: 21, }; /*...*/ } // Type-checks! No type assertions needed! let el = ; ```
`JSX.LibraryManagedAttributes` nuance for library authors The above implementations work fine for App creators, but sometimes you want to be able to export `GreetProps` so that others can consume it. The problem here is that the way `GreetProps` is defined, `age` is a required prop when it isn't because of `defaultProps`. The insight to have here is that [`GreetProps` is the _internal_ contract for your component, not the _external_, consumer facing contract](https://github.com/typescript-cheatsheets/react/issues/66#issuecomment-453878710). You could create a separate type specifically for export, or you could make use of the `JSX.LibraryManagedAttributes` utility: ```tsx // internal contract, should not be exported out type GreetProps = { age?: number; }; class Greet extends Component { static defaultProps = { age: 21 }; } // external contract export type ApparentGreetProps = JSX.LibraryManagedAttributes< typeof Greet, GreetProps >; ``` ``This will work properly, although hovering over`ApparentGreetProps`may be a little intimidating. You can reduce this boilerplate with the`ComponentProps` utility detailed below.
## Consuming Props of a Component with defaultProps A component with `defaultProps` may seem to have some required props that actually aren't. ### Problem Statement Here's what you want to do: ```tsx interface IProps { name: string; } const defaultProps = { age: 25, }; const GreetComponent = ({ name, age }: IProps & typeof defaultProps) => (
{`Hello, my name is ${name}, ${age}`}
); GreetComponent.defaultProps = defaultProps; const TestComponent = (props: React.ComponentProps) => { return

; }; // Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }' const el = ; ``` ### Solution Define a utility that applies `JSX.LibraryManagedAttributes`: ```tsx type ComponentProps = T extends | React.ComponentType | React.Component ? JSX.LibraryManagedAttributes : never; const TestComponent = (props: ComponentProps) => { return

; }; // No error const el = ; ``` [_See this in TS Playground_](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwBQdMAnmFnAMImQB2W3MABWJhUAHgAqAPjgBeOOLhYAHjD4ATdNjwwAdJ3ARe-cSyyjg3AlihwB0gD6Yqu-Tz4xzl67cl04cAH44ACkAZQANHQAZYAAjKGQoJgBZZG5kAHMsNQBBGBgoOIBXVTFxABofPzgALjheADdrejoLVSgCPDYASSEIETgAb2r0kCw61AKLDPoAXzpcQ0m4NSxOooAbQWF0OWH-TPG4ACYAVnK6WfpF7mWAcUosGFdDd1k4AApB+uQxysO4LM6r0dnAAGRwZisCAEFZrZCbbb9VAASlk0g+1VEamADUkgwABgAJLAbDYQSogJg-MZwYDoAAkg1GWFmlSZh1mBNmogA9Di8XQUfQHlgni8jLpVustn0BnJpQjZTsWrzeXANsh2gwbstxFhJhK3nIPmAdnUjfw5WIoVgYXBReKuK9+JI0TJpPs4JQYEUoNw4KIABYARjgvN8VwYargADkIIooMQoAslvBSe8JAbns7JTSsDIyAQIBAyOHJDQgA) ## Misc Discussions and Knowledge
Why does React.FC break defaultProps? You can check the discussions here: - https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680 - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30695 - https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/87 This is just the current state and may be fixed in future.
TypeScript 2.9 and earlier For TypeScript 2.9 and earlier, there's more than one way to do it, but this is the best advice we've yet seen: ```ts type Props = Required & { /* additional props here */ }; export class MyComponent extends React.Component { static defaultProps = { foo: "foo", }; } ``` Our former recommendation used the `Partial type` feature in TypeScript, which means that the current interface will fulfill a partial version on the wrapped interface. In that way we can extend defaultProps without any changes in the types! ```ts interface IMyComponentProps { firstProp?: string; secondProp: IPerson[]; } export class MyComponent extends React.Component { public static defaultProps: Partial = { firstProp: "default", }; } ``` The problem with this approach is it causes complex issues with the type inference working with `JSX.LibraryManagedAttributes`. Basically it causes the compiler to think that when creating a JSX expression with that component, that all of its props are optional. [See commentary by @ferdaber here](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/57) and [here](https://github.com/typescript-cheatsheets/react/issues/61).
[Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## Typing Component Props This is intended as a basic orientation and reference for React developers familiarizing with TypeScript. ## Basic Prop Types Examples A list of TypeScript types you will likely use in a React+TypeScript app: ```tsx type AppProps = { message: string; count: number; disabled: boolean; /** array of a type! */ names: string[]; /** string literals to specify exact string values, with a union type to join them together */ status: "waiting" | "success"; /** any object as long as you dont use its properties (NOT COMMON but useful as placeholder) */ obj: object; obj2: {}; // almost the same as `object`, exactly the same as `Object` /** an object with any number of properties (PREFERRED) */ obj3: { id: string; title: string; }; /** array of objects! (common) */ objArr: { id: string; title: string; }[]; /** a dict object with any number of properties of the same type */ dict1: { [key: string]: MyTypeHere; }; dict2: Record; // equivalent to dict1 /** any function as long as you don't invoke it (not recommended) */ onSomething: Function; /** function that doesn't take or return anything (VERY COMMON) */ onClick: () => void; /** function with named prop (VERY COMMON) */ onChange: (id: number) => void; /** alternative function type syntax that takes an event (VERY COMMON) */ onClick(event: React.MouseEvent): void; /** an optional prop (VERY COMMON!) */ optional?: OptionalType; }; ``` Notice we have used the TSDoc `/** comment */` style here on each prop. You can and are encouraged to leave descriptive comments on reusable components. For a fuller example and discussion, see our [Commenting Components](https://react-typescript-cheatsheet.netlify.app/docs/advanced/misc_concerns/#commenting-components) section in the Advanced Cheatsheet. ## Useful React Prop Type Examples Relevant for components that accept other React components as props. ```tsx export declare interface AppProps { children1: JSX.Element; // bad, doesnt account for arrays children2: JSX.Element | JSX.Element[]; // meh, doesn't accept strings children3: React.ReactChildren; // despite the name, not at all an appropriate type; it is a utility children4: React.ReactChild[]; // better, accepts array children children: React.ReactNode; // best, accepts everything (see edge case below) functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type style?: React.CSSProperties; // to pass through style props onChange?: React.FormEventHandler; // form events! the generic parameter is the type of event.target // more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring props: Props & React.ComponentPropsWithoutRef<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref props2: Props & React.ComponentPropsWithRef; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref } ```
Small `React.ReactNode` edge case This code typechecks but has a runtime error: ```tsx type Props = { children: React.ReactNode; }; function Comp({ children }: Props) { return
{children}
; } function App() { return {{}}; // Runtime Error: Objects not valid as React Child! } ``` This is because `ReactNode` includes `ReactFragment` which allows a `{}` type, which is [too wide](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/37596#issue-480260937). Fixing this would break a lot of libraries, so for now you just have to be mindful that `ReactNode` is not absolutely bulletproof. [Thanks @pomle for raising this.](https://github.com/typescript-cheatsheets/react/issues/357)
JSX.Element vs React.ReactNode? Quote [@ferdaber](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/57): A more technical explanation is that a valid React node is not the same thing as what is returned by `React.createElement`. Regardless of what a component ends up rendering, `React.createElement` always returns an object, which is the `JSX.Element` interface, but `React.ReactNode` is the set of all possible return values of a component. - `JSX.Element` -> Return value of `React.createElement` - `React.ReactNode` -> Return value of a component
[More discussion: Where ReactNode does not overlap with JSX.Element](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/129) [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## Types or Interfaces? You can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use? Here's a helpful rule of thumb: - always use `interface` for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via _declaration merging_ if some definitions are missing. - consider using `type` for your React Component Props and State, for consistency and because it is more constrained. You can read more about the reasoning behind this rule of thumb in [Interface vs Type alias in TypeScript 2.7](https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c). > Note: At scale, there are performance reasons to prefer interfaces ([see official Microsoft notes on this](https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections)) but [take this with a grain of salt](https://news.ycombinator.com/item?id=25201887) Types are useful for union types (e.g. `type MyType = TypeA | TypeB`) whereas Interfaces are better for declaring dictionary shapes and then `implementing` or `extending` them. ### Useful table for Types vs Interfaces It's a nuanced topic, don't get too hung up on it. Here's a handy table: | Aspect | Type | Interface | | ----------------------------------------------- | :--: | :-------: | | Can describe functions | ✅ | ✅ | | Can describe constructors | ✅ | ✅ | | Can describe tuples | ✅ | ✅ | | Interfaces can extend it | ⚠️ | ✅ | | Classes can extend it | 🚫 | ✅ | | Classes can implement it (`implements`) | ⚠️ | ✅ | | Can intersect another one of its kind | ✅ | ⚠️ | | Can create a union with another one of its kind | ✅ | 🚫 | | Can be used to create mapped types | ✅ | 🚫 | | Can be mapped over with mapped types | ✅ | ✅ | | Expands in error messages and logs | ✅ | 🚫 | | Can be augmented | 🚫 | ✅ | | Can be recursive | ⚠️ | ✅ | ⚠️ In some cases (source: [Karol Majewski](https://twitter.com/karoljmajewski/status/1082413696075382785)) [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## getDerivedStateFromProps Before you start using `getDerivedStateFromProps`, please go through the [documentation](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [You Probably Don't Need Derived State](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). Derived State can be easily achieved using hooks which can also help set up memoization easily. Here are a few ways in which you can annotate `getDerivedStateFromProps` 1. If you have explicitly typed your derived state and want to make sure that the return value from `getDerivedStateFromProps` conforms to it. ```tsx class Comp extends React.Component { static getDerivedStateFromProps( props: Props, state: State ): Partial | null { // } } ``` 2. When you want the function's return value to determine your state. ```tsx class Comp extends React.Component< Props, ReturnType > { static getDerivedStateFromProps(props: Props) {} } ``` 3. When you want derived state with other state fields and memoization ```tsx type CustomValue = any; interface Props { propA: CustomValue; } interface DefinedState { otherStateField: string; } type State = DefinedState & ReturnType; function transformPropsToState(props: Props) { return { savedPropA: props.propA, // save for memoization derivedState: props.propA, }; } class Comp extends React.PureComponent { constructor(props: Props) { super(props); this.state = { otherStateField: "123", ...transformPropsToState(props), }; } static getDerivedStateFromProps(props: Props, state: State) { if (isEqual(props.propA, state.savedPropA)) return null; return transformPropsToState(props); } } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOYAZwFEBHAVxQBs5tcD2IATFHQAWAOnpJWHMuQowAnmCRwAwizoxcANQ4tlAXjgoAdvIDcFYMZhIomdMoAKOMHTgBvCnDhgXAQQAuVXVNEB12PQtyAF9La1t7NGUAESRMKyR+AGUYFBsPLzgIGGFbHLykADFgJHZ+II0oKwBzKNjyBSU4cvzDVPTjTJ7lADJEJBgWKGMAFUUkAB5OpAhMOBgoEzpMaBBnCFcZiGGAPijMFmMMYAhjdc3jbd39w+PcmwAKXwO6IJe6ACUBXI3iIk2mwO83joKAAbpkXoEfC46KJvmA-AAaOAAehxcBh8K40DgICQIAgwAAXnkbsZCt5+LZgPDsu8kEF0aj0X5CtE2hQ0OwhG4VLgwHAkAAPGzGfhuZDoGCiRxTJBi8C3JDWBb-bGnSFwNC3RosDDQL4ov4ooGeEFQugsJRQS0-AFRKHrYT0UQaCpwQx2z3eYqlKDDaq1epwABEAEYAEwAZhjmIZUNEmY2Wx2UD2KKOw1drgB6f5fMKfpgwDQcGaE1STVZEZw+Z+xd+cD1BPZQWGtvTwDWH3ozDY7A7aP82KrSF9cIR-gBQLBUzuxhY7HYHqhq4h2ceubbryLXPdFZiQA) ## Forms and Events If performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can just use [type inference and contextual typing](https://www.typescriptlang.org/docs/handbook/type-inference.html#contextual-typing): ```tsx const el = ( )); ```
Side note: the `ref` you get from `forwardRef` is mutable so you can assign to it if needed. This was done [on purpose](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43265/). You can make it immutable if you have to - assign `React.Ref` if you want to ensure nobody reassigns it: ```tsx type Props = { children: React.ReactNode; type: "submit" | "button" }; export type Ref = HTMLButtonElement; export const FancyButton = React.forwardRef(( props: Props, ref: React.Ref // <-- here! ) => ( )); ```
If you are grabbing the props of a component that forwards refs, use [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770). More info: https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315 You may also wish to do [Conditional Rendering with `forwardRef`](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/167). [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## Portals Using `ReactDOM.createPortal`: ```tsx const modalRoot = document.getElementById("modal-root") as HTMLElement; // assuming in your html file has a div with id 'modal-root'; export class Modal extends React.Component { el: HTMLElement = document.createElement("div"); componentDidMount() { modalRoot.appendChild(this.el); } componentWillUnmount() { modalRoot.removeChild(this.el); } render() { return ReactDOM.createPortal(this.props.children, this.el); } } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWRYmAEQHkBZObXAo9GAWgBNcZchTQQAdgGd4ICHxQAbBBAjwAvHAFoAriCRiYAOgDmSGAFF5SXfoBCATwCSfABQAiGXPk8cK1wEo4FAk4AAkAFWYAGQsrPRgAbgoAeiTAiQkdYDEjOCy4OwgtKDgACxgQeTZgS1KgwI1gADc4AHdgGBLcvgIPBW9lGHxE4XIkAA9qeDR5IODmWQU4cZg9PmDkbgMAYVxIMTi4AG8KOCX5AC5QiOjLazUNCG07gzQuFZi7tz4m-2GTuFE4HEcXowD48y0+mcAWO5FOp16igGBhQYDAqy2JWqLg6wAkBiQ8j8w1OAF8KP9AXs4gB1aryACqYhkkJg0KO-wRCyRKgMRBkjSQmOxzlx+MJxP+5JGpyIYj4SCg7Nh8LgRBgRTEtG4TGYLzeSAACtAYApRVj8WAcGB8WgsfI+HKADRwMUEokkuDS0lAA)
Using hooks Same as above but using hooks ```tsx import React, { useEffect, useRef } from "react"; import { createPortal } from "react-dom"; const modalRoot = document.querySelector("#modal-root") as HTMLElement; const Modal: React.FC<{}> = ({ children }) => { const el = useRef(document.createElement("div")); useEffect(() => { // Use this in case CRA throws an error about react-hooks/exhaustive-deps const current = el.current; // We assume `modalRoot` exists with '!' modalRoot!.appendChild(current); return () => void modalRoot!.removeChild(current); }, []); return createPortal(children, el.current); }; export default Modal; ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoUSWOAbzjSJRiQAVoYUAbOAXzmy4CTDAFoAJrjLkKAellwUAZyUBXEMAB2Aczha4ATwiqocABYwQPTMC5JzyxXHHAAbnADuwGGb3iCIBDi3KI4EDD4ANwUFGgQmkrwALJB3ABciMQwAHQAYgDCADy0vAB8cAC8cAAU9GhmtuJEmnwAlJXltBRwcPJwAKIgqlzM9j72aCMqDLiQmkiaEUp6CZyaaPauKFDAKABGdp7evihwRJjdM6twSDxVyOg5qkpIyJjVkmjqCzmMqCz9OwgH7VABELlcoNarWiMnIPQeGGyzyQ-UwmCQGGq1XaFU6lx6fQA6vZlGpgXAAAaBYJcBAQcKUm4AD2AiWWXh8BAAhNIej04tcadx6eFKs4IF9gYtsgBHVRIKAGADKt0xMGgYIAxMKuKEGTAoYplgAJAAqSQAMoCkNKYLD+XBdaKYNzsigwGAFuJ8g0uOJqrdsl8oM0YDCCWckDATC0cR04K4IMB-M6DW6iIFXEhfY1A1xgyYwxH4XwADRwADaAF0S5c+gBJVaofwQTBU26UivjK6cLSKvTLHuU86F0M-SmXIgxqAtP6jdiwbjVeqNZoVoMh4uw3iwuQKZ4obRIGLkTCqdYwYDxOAAQU98a6pcFiSrSjMEA8KVpFZeMGVH5fqkXDVuKiJPC8yqcCw1SYNwLwlj006xjUkaFBCpSRoSChGKoDAoC08EQHAYCqPAPhsishjGKYiTMMAaDmJY1i2CepaOuhbh+BUoK6vq4SgqUhSyBhWF0O+n7ftwcAAGQyah7GOnAhRSVwmGKUpykQmJmmJAYdgVLQT6aSZzhsmAIwGBkoLaDs4igmWOkmRZ6BIA2LAgEo1kbIsioOU5mlmEgwDaBY1kAIwAAyRa4Zj+RpplHOIPgZPgUUxWY+COQlpl7OgADWtnGJo4jWVA2h5dUkVltVtXZOFrTxYlSkAF5NuISDMhkACc3XZc1PS8LwAVwOpA1wA2+B4KcurcrQoJwKCw05UphR7GRGotHpBlGXlaCFTgF6lYtYAegYKAeA0YBLfw8T5FwDH5YZ8Z4nAf4AZJwGwfBSCtGUkwQC8wnrTAm1jYlwmiStwmqeDjp-WJa0bTed0Pftz24uU72Aap1QwFACp-aUEkeHAqnA8jmhw-yfREK+bbUSYiiemhIluODrQULwQA)
Modal Component Usage Example: ```tsx function App() { const [showModal, setShowModal] = React.useState(false); return (
// you can also put this in your static html file {showModal && (
I'm a modal!{" "}
)} // rest of your app
); } ```
Context of Example This example is based on the [Event Bubbling Through Portal](https://reactjs.org/docs/portals.html#event-bubbling-through-portals) example of React docs.
## Error Boundaries ### Option 1: Using react-error-boundary [React-error-boundary](https://github.com/bvaughn/react-error-boundary) - is a lightweight package ready to use for this scenario with TS support built-in. This approach also lets you avoid class components that are not that popular anymore. ### Options 2: Writing your custom error boundary component If you don't want to add a new npm package for this, you can also write your own `ErrorBoundary` component. ```jsx import React, { Component, ErrorInfo, ReactNode } from "react"; interface Props { children: ReactNode; } interface State { hasError: boolean; } class ErrorBoundary extends Component { public state: State = { hasError: false }; public static getDerivedStateFromError(_: Error): State { // Update state so the next render will show the fallback UI. return { hasError: true }; } public componentDidCatch(error: Error, errorInfo: ErrorInfo) { console.error("Uncaught error:", error, errorInfo); } public render() { if (this.state.hasError) { return

Sorry.. there was an error

; } return this.props.children; } } export default ErrorBoundary; ``` [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). ## Concurrent React/React Suspense _Not written yet._ watch for more on React Suspense and Time Slicing. [Something to add? File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new). # Troubleshooting Handbook: Types > ⚠️ Have you read [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ?) Your answer might be there! Facing weird type errors? You aren't alone. This is the hardest part of using TypeScript with React. Be patient - you are learning a new language after all. However, the more you get good at this, the less time you'll be working _against_ the compiler and the more the compiler will be working _for_ you! Try to avoid typing with `any` as much as possible to experience the full benefits of TypeScript. Instead, let's try to be familiar with some of the common strategies to solve these issues. ## Union Types and Type Guarding Union types are handy for solving some of these typing problems: ```tsx class App extends React.Component< {}, { count: number | null; // like this } > { state = { count: null, }; render() { return
this.increment(1)}>{this.state.count}
; } increment = (amt: number) => { this.setState((state) => ({ count: (state.count || 0) + amt, })); }; } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeCnDgBvAL4AaBcs2K0EAK48YALjg89IAEZIocAD6m91agG44AejdxqwANZI4MAAWwHSaKhQAfFrkinQwKNxwALzRijr6hiZmTmHOmkT81gAUAJSpaUQwelA8cLJ8wABucBA8Yt5oPklKpclRQSEiwDxoRCAyRQCMJSoRSgN0InEJSCK6BjAqsm4NjRF5MXDhh8OjSOOGyXBFKCDGDpbWZUlRStoBwYt0SDAAyvHcIrLRIva5vQ5pODrTLXYGraHwWz2AAMZQA1HBbjB3ioSiUDooVAcVEA) **Type Guarding**: Sometimes Union Types solve a problem in one area but create another downstream. If `A` and `B` are both object types, `A | B` isn't "either A or B", it is "A or B or both at once", which causes some confusion if you expected it to be the former. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example: ```ts interface Admin { role: string; } interface User { email: string; } // Method 1: use `in` keyword function redirect(user: Admin | User) { if ("role" in user) { // use the `in` operator for typeguards since TS 2.7+ routeToAdminPage(user.role); } else { routeToHomePage(user.email); } } // Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough function isAdmin(user: Admin | User): user is Admin { return (user as any).role !== undefined; } ``` [View in the TypeScript Playground](https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoC4AOxiSk3STgEEATEGuAbwrjhwAbJAC44AZxhQaAcwDcFAL5Va9RmmYBVcfR584SECmCCxk6dXlKKFTAFdqGYBGoCIdugBUI7TtQAKKDJIABTiwDLUwJjA9ACUeuT80XBhEVExugC8OQR2OlAIEML4CbxJ-AJIMHZQrvi+NGQVinDWlOT2jjDOrjgeSN4AErhIgcFpkdGxUGX6KZMZM3A5WQSGxoKliZVVNXUEIyBIYEFIzfzK5FcUAPS3cACy1QAWEGxwAIxi+cwABjQ-nAANZIACeAHdoGxbA4nC4qmxgEQMCFflAxI1XAAfODaeI7ODREIAIiESBJRNc6LKcHucF+cBgL3+gLgEDA9BQMGgcEwvJgYM5MjsKCgbHEEhoGjgngAynAAEwAOgA7ABqfT8fpeHwcGjjULo5XkuIKFoGQQ6Qna9y6o5jM5ogrKjYmM36K43cj057M95KsRofI8vCCzlwEVitgAGjgbAgSElzOY4hQxyZL1kVPZgjYunlcAAbvRwi5JbyISyiHAAdQgcBxLQDNR3DIXrDur0ieIsc76Jj9Ti8QU4j8Cj3WEPCUR9q5+1A4ChJShqGC4ibiswAIS5Bz5mLUJAw65AA) Method 2 is also known as [User-Defined Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) and can be really handy for readable code. This is how TS itself refines types with `typeof` and `instanceof`. If you need `if...else` chains or the `switch` statement instead, it should "just work", but look up [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions) if you need help. (See also: [Basarat's writeup](https://basarat.gitbook.io/typescript/type-system/discriminated-unions)). This is handy in typing reducers for `useReducer` or Redux. ## Optional Types If a component has an optional prop, add a question mark and assign during destructure (or use defaultProps). ```tsx class MyComponent extends React.Component<{ message?: string; // like this }> { render() { const { message = "default" } = this.props; return
{message}
; } } ``` You can also use a `!` character to assert that something is not undefined, but this is not encouraged. _Something to add? [File an issue](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet/issues/new) with your suggestions!_ ## Enum Types **We recommend avoiding using enums as far as possible**. Enums have a few [documented issues](https://fettblog.eu/tidy-typescript-avoid-enums/) (the TS team [agrees](https://twitter.com/orta/status/1348966323271987201?s=20)). A simpler alternative to enums is just declaring a union type of string literals: ```tsx export declare type Position = "left" | "right" | "top" | "bottom"; ``` If you must use enums, remember that enums in TypeScript default to numbers. You will usually want to use them as strings instead: ```tsx export enum ButtonSizes { default = "default", small = "small", large = "large", } // usage export const PrimaryButton = ( props: Props & React.HTMLProps ) =>