Cheatsheet for using React with TypeScript.

Web docs | Contribute! | Ask!
👋 This repo is maintained by @eps1lon and @filiptammergard. We're so happy you want to try out React with TypeScript! If you see anything wrong or missing, please file an issue! 👍
- The Basic Cheatsheet 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 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 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 specifically teaches people to write HOCs with examples.
- Familiarity with Generics is necessary.
⚠️ This is the newest cheatsheet, all assistance is welcome.
Expand Table of Contents
- React TypeScript Cheatsheet
- Basic Cheatsheet
- Basic Cheatsheet Table of Contents
- Section 1: Setup
- Section 2: Getting Started
- Function Components
- Hooks
- useState
- useCallback
- useReducer
- useEffect / useLayoutEffect
- useRef
- useImperativeHandle
- Custom Hooks
- More Hooks + TypeScript reading:
- Example React Hooks + TypeScript Libraries:
- Class Components
- Typing getDerivedStateFromProps
- You May Not Need
defaultProps
- Typing
defaultProps
- Consuming Props of a Component with defaultProps
- Misc Discussions and Knowledge
- Typing Component Props
- Basic Prop Types Examples
- Useful React Prop Type Examples
- Types or Interfaces?
- getDerivedStateFromProps
- Forms and Events
- Context
- Basic example
- Without default context value
- forwardRef/createRef
- Generic forwardRefs
- More Info
- Portals
- Error Boundaries
- Concurrent React/React Suspense
- Troubleshooting Handbook: Types
- Troubleshooting Handbook: Operators
- Troubleshooting Handbook: Utilities
- Troubleshooting Handbook: tsconfig.json
- Troubleshooting Handbook: Fixing bugs in official typings
- Troubleshooting Handbook: Globals, Images and other non-TS files
- Editor Tooling and Integration
- Linting
- Other React + TypeScript resources
- Recommended React + TypeScript talks
- Time to Really Learn TypeScript
- Example App
- My question isn't answered here!
- Contributors
- Basic Cheatsheet
You can use this cheatsheet for reference at any skill level, but basic understanding of React and TypeScript is assumed. Here is a list of prerequisites:
- Basic understanding of React.
- Familiarity with TypeScript Basics and Everyday Types.
In the cheatsheet we assume you are using the latest versions of React and TypeScript.
React has documentation for how to start a new React project with some of the most popular frameworks. Here's how to start them with TypeScript:
- Next.js:
npx create-next-app@latest --ts
- Remix:
npx create-remix@latest
- Gatsby:
npm init gatsby --ts
- Expo:
npx create-expo-app -t with-typescript
There are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.
These can be written as normal functions that take a props
argument and return a JSX element.
// Declaring type of props - see "Typing Component Props" for more examples type AppProps = { message: string; }; /* use `interface` if exporting so that consumers can extend */ // Easiest way to declare a Function Component; return type is inferred. const App = ({ message }: AppProps) => <div>{message}div>; // You can choose to annotate the return type so an error is raised if you accidentally return some other type const App = ({ message }: AppProps): React.JSX.Element => <div>{message}div>; // You can also inline the type declaration; eliminates naming the prop types, but looks repetitive const App = ({ message }: { message: string }) => <div>{message}div>; // Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer. // With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged. const App: React.FunctionComponent<{ message: string }> = ({ message }) => ( <div>{message}div> ); // or const App: React.FC<AppProps> = ({ message }) => <div>{message}div>;
Tip: You might use Paul Shen's VS Code Extension to automate the type destructure declaration (incl a keyboard shortcut).
Why is React.FC
not needed? What about React.FunctionComponent
/React.VoidFunctionComponent
?
You may see this in many React+TypeScript codebases:
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}div>
);
However, the general consensus today is that React.FunctionComponent
(or the shorthand React.FC
) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is even discouraged. 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.
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
, anddefaultProps
.- Note that there are some known issues using
defaultProps
withReact.FunctionComponent
. See this issue for details. We maintain a separatedefaultProps
section you can also look up.
- Note that there are some known issues using
-
Before the React 18 type updates,
React.FunctionComponent
provided an implicit definition ofchildren
(see below), which was heavily debated and is one of the reasonsReact.FC
was removed from the Create React App TypeScript template.
// before React 18 types
const Title: React.FunctionComponent<{ title: string }> = ({
children,
title,
}) => <div title={title}>{children}div>;
(Deprecated)Using React.VoidFunctionComponent
or React.VFC
instead
In @types/react 16.9.48, the React.VoidFunctionComponent
or React.VFC
type was added for typing children
explicitly.
However, please be aware that React.VFC
and React.VoidFunctionComponent
were deprecated in React 18 (DefinitelyTyped/DefinitelyTyped#59882), so this interim solution is no longer necessary or recommended in React 18+.
Please use regular function components or React.FC
instead.
type Props = { foo: string };
// OK now, in future, error
const FunctionComponent: React.FunctionComponent<Props> = ({
foo,
children,
}: Props) => {
return (
<div>
{foo} {children}
</div>
); // OK
};
// Error now, in future, deprecated
const VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({
foo,
children,
}) => {
return (
<div>
{foo}
{children}
</div>
);
};
- 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
.
Hooks are supported in @types/react
from v16.8 up.
Type inference works very well for simple values:
const [state, setState] = useState(false);
// `state` is inferred to be a boolean
// `setState` only takes booleans
See also the 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:
const [user, setUser] = useState<User | null>(null);
// later...
setUser(newUser);
You can also use type assertions if a state is initialized soon after setup and always has a value after:
const [user, setUser] = useState<User>({} as User);
// later...
setUser(newUser);
This temporarily "lies" to the TypeScript compiler that {}
is of type User
. You should follow up by setting the user
state — if you don't, the rest of your code may rely on the fact that user
is of type User
and that may lead to runtime errors.
You can type the useCallback
just like any other function.
const memoizedCallback = useCallback(
(param1: string, param2: number) => {
console.log(param1, param2)
return { ok: true }
},
[...],
);
/**
* VSCode will show the following type:
* const memoizedCallback:
* (param1: string, param2: number) => { ok: boolean }
*/
Note that for React < 18, the function signature of useCallback
typed arguments as any[]
by default:
function useCallback<T extends (...args: any[]) => any>(
callback: T,
deps: DependencyList
): T;
In React >= 18, the function signature of useCallback
changed to the following:
function useCallback<T extends Function>(callback: T, deps: DependencyList): T;
Therefore, the following code will yield "Parameter 'e' implicitly has an 'any' type.
" error in React >= 18, but not <17.
// @ts-expect-error Parameter 'e' implicitly has 'any' type.
useCallback((e) => {}, []);
// Explicit 'any' type.
useCallback((e: any) => {}, []);
You can use Discriminated Unions for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.
import { useReducer } from "react";
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] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "decrement", payload: "5" })}>
-
button>
<button onClick={() => dispatch({ type: "increment", payload: 5 })}>
+
button>
>
);
}
View in the TypeScript Playground
Usage with Reducer
from redux
In case you use the 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:
import { Reducer } from 'redux';
export function reducer: Reducer<AppState, Action>() {}
Both of useEffect
and useLayoutEffect
are used for performing side effects and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. 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:
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
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;
}
In TypeScript, useRef
returns a reference that is either read-only or mutable, depends on whether your type argument fully covers the initial value or not. Choose one that suits your use case.
To access a DOM element: provide only the element type as argument, and use null
as initial value. In this case, the returned reference will have a read-only .current
that is managed by React. TypeScript expects you to give this ref to an element's ref
prop:
function Foo() {
// - If possible, prefer as specific as possible. For example, HTMLDivElement
// is better than HTMLElement and way better than Element.
// - Technical-wise, this returns RefObject
const divRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// Note that ref.current may be null. This is expected, because you may
// conditionally render the ref-ed element, or you may forget to assign it
if (!divRef.current) throw Error("divRef is not assigned");
// Now divRef.current is sure to be HTMLDivElement
doSomethingWith(divRef.current);
});
// Give the ref to an element so React can manage it for you
return <div ref={divRef}>etcdiv>;
}
If you are sure that divRef.current
will never be null, it is also possible to use the non-null assertion operator !
:
const divRef = useRef<HTMLDivElement>(null!);
// Later... No need to check if it is null
doSomethingWith(divRef.current);
Note that you are opting out of type safety here - you will have a runtime error if you forget to assign the ref to an element in the render, or if the ref-ed element is conditionally rendered.
Tip: Choosing which HTMLElement
to use
Refs demand specificity - it is not enough to just specify any old HTMLElement
. If you don't know the name of the element type you need, you can check lib.dom.ts or make an intentional type error and let the language service tell you:
To have a mutable value: provide the type you want, and make sure the initial value fully belongs to that type:
function Foo() {
// Technical-wise, this returns MutableRefObject
const intervalRef = useRef<number | null>(null);
// You manage the ref yourself (that's why it's called MutableRefObject!)
useEffect(() => {
intervalRef.current = setInterval(...);
return () => clearInterval(intervalRef.current);
}, []);
// The ref is not passed to any element's "ref" prop
return <button onClick={/* clearInterval the ref */}>Cancel timerbutton>;
}
Based on this Stackoverflow answer:
// Countdown.tsx
// Define the handle types which will be passed to the forwardRef
export type CountdownHandle = {
start: () => void;
};
type CountdownProps = {};
const Countdown = forwardRef<CountdownHandle, CountdownProps>((props, ref) => {
useImperativeHandle(ref, () => ({
// start() has type inference here
start() {
alert("Start");
},
}));
return <div>Countdowndiv>;
});
// The component uses the Countdown component
import Countdown, { CountdownHandle } from "./Countdown.tsx";
function App() {
const countdownEl = useRef<CountdownHandle>(null);
useEffect(() => {
if (countdownEl.current) {
// start() has type inference here as well
countdownEl.current.start();
}
}, []);
return <Countdown ref={countdownEl} />;
}
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:
import { useState } from "react";
export function useLoading() {
const [isLoading, setState] = useState(false);
const load = (aPromise: Promise<any>) => {
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
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, you can also assert or define the function return types:
import { useState } from "react";
export function useLoading() {
const [isLoading, setState] = useState(false);
const load = (aPromise: Promise<any>) => {
setState(true);
return aPromise.finally(() => setState(false));
};
return [isLoading, load] as [
boolean,
(aPromise: Promise<any>) => Promise<any>
];
}
A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:
function tuplify<T extends any[]>(...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.
- 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.
- https://github.com/mweststrate/use-st8
- https://github.com/palmerhq/the-platform
- https://github.com/sw-yx/hooks
Something to add? File an issue.
Within TypeScript, React.Component
is a generic type (aka React.Component
), so you want to provide it with (optional) prop and state type parameters:
type MyProps = {
// using `interface` is also ok
message: string;
};
type MyState = {
count: number; // like this
};
class App extends React.Component<MyProps, MyState> {
state: MyState = {
// optional second annotation for better type inference
count: 0,
};
render() {
return (
<div>
{this.props.message} {this.state.count}
div>
);
}
}
View in the TypeScript Playground
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.
No need for readonly
You often see sample code include readonly
to mark props and state immutable:
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!)
Class Methods: Do it like normal, but just remember any arguments for your functions also need to be typed:
class App extends React.Component<{ message: string }, { count: number }> {
state = { count: 0 };
render() {
return (
<div onClick={() => this.increment(1)}>
{this.props.message} {this.state.count}
div>
);
}
increment = (amt: number) => {
// like this
this.setState((state) => ({
count: state.count + amt,
}));
};
}
View in the TypeScript Playground
Class Properties: If you need to declare class properties for later use, just declare it like state
, but without assignment:
class App extends React.Component<{
message: string;
}> {
pointer: number; // like this
componentDidMount() {
this.pointer = 3;
}
render() {
return (
<div>
{this.props.message} and {this.pointer}
div>
);
}
}
View in the TypeScript Playground
Something to add? File an issue.
Before you start using getDerivedStateFromProps
, please go through the documentation and You Probably Don't Need Derived State. 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
- If you have explicitly typed your derived state and want to make sure that the return value from
getDerivedStateFromProps
conforms to it.
class Comp extends React.Component<Props, State> {
static getDerivedStateFromProps(
props: Props,
state: State
): Partial<State> | null {
//
}
}
- When you want the function's return value to determine your state.
class Comp extends React.Component<
Props,
ReturnType<typeof Comp["getDerivedStateFromProps"]>
> {
static getDerivedStateFromProps(props: Props) {}
}
- When you want derived state with other state fields and memoization
type CustomValue = any;
interface Props {
propA: CustomValue;
}
interface DefinedState {
otherStateField: string;
}
type State = DefinedState & ReturnType<typeof transformPropsToState>;
function transformPropsToState(props: Props) {
return {
savedPropA: props.propA, // save for memoization
derivedState: props.propA,
};
}
class Comp extends React.PureComponent<Props, State> {
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
As per this tweet, defaultProps will eventually be deprecated. You can check the discussions here:
- Original tweet
- More info can also be found in this article
The consensus is to use object default values.
Function Components:
type GreetProps = { age?: number };
const Greet = ({ age = 21 }: GreetProps) => // etc
Class Components:
type GreetProps = {
age?: number;
};
class Greet extends React.Component<GreetProps> {
render() {
const { age = 21 } = this.props;
/*...*/
}
}
let el = <Greet age={3} />;
Type inference improved greatly for defaultProps
in TypeScript 3.0+, although some edge cases are still problematic.
Function Components
// using typeof as a shortcut; note that it hoists!
// you can also declare the type of DefaultProps if you choose
// e.g. https://github.com/typescript-cheatsheets/react/issues/415#issuecomment-841223219
type GreetProps = { age: number } & typeof defaultProps;
const defaultProps = {
age: 21,
};
const Greet = (props: GreetProps) => {
// etc
};
Greet.defaultProps = defaultProps;
For Class components, there are a couple ways to do it (including using the Pick
utility type) but the recommendation is to "reverse" the props definition:
type GreetProps = typeof Greet.defaultProps & {
age: number;
};
class Greet extends React.Component<GreetProps> {
static defaultProps = {
age: 21,
};
/*...*/
}
// Type-checks! No type assertions needed!
let el = <Greet age={3} />;
React.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. You could create a separate type specifically for export, or you could make use of the React.JSX.LibraryManagedAttributes
utility:
// internal contract, should not be exported out
type GreetProps = {
age: number;
};
class Greet extends Component<GreetProps> {
static defaultProps = { age: 21 };
}
// external contract
export type ApparentGreetProps = React.JSX.LibraryManagedAttributes<
typeof Greet,
GreetProps
>;
This will work properly, although hovering overApparentGreetProps
may be a little intimidating. You can reduce this boilerplate with theComponentProps
utility detailed below.
A component with defaultProps
may seem to have some required props that actually aren't.
Here's what you want to do:
;">interface IProps { name: string; } const defaultProps = { age: 25, }; const GreetComponent = ({ name, age }: IProps & typeof defaultProps) => ( <div>{`Hello, my name is ${name}, ${age}`}div> ); GreetComponent.defaultProps = defaultProps; const TestComponent = (props: React.ComponentProps<typeof GreetComponent>) => { return <h1 />; }; // Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }' const el = <TestComponent name="foo" />;