React+TypeScript Cheatsheets

Cheatsheets for experienced React developers getting started with TypeScript


react + ts logo

Web docs | Español | Português | Contribute! | Ask!

👋 This repo is maintained by @swyx, @eps1lon and @filiptammergard. We're so happy you want to try out TypeScript with React! If you see anything wrong or missing, please file an issue! 👍


All Contributors | Discord | Tweet

All React + TypeScript Cheatsheets

  • 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.

Basic Cheatsheet

Basic Cheatsheet Table of Contents

Expand Table of Contents

Section 1: Setup

Prerequisites

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:

In the cheatsheet we assume you are using the latest versions of React and TypeScript.

React and TypeScript starter kits

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

Try React and TypeScript online

There are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.

Section 2: Getting Started

Function Components

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 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>
);

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, and defaultProps.

    • Note that there are some known issues using defaultProps with React.FunctionComponent. See this issue for details. We maintain a separate defaultProps section you can also look up.
  • Before the React 18 type updates, React.FunctionComponent provided an implicit definition of children (see below), which was heavily debated and is one of the reasons React.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

Hooks are supported in @types/react from v16.8 up.

useState

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.

useCallback

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) => {}, []);

useReducer

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<State, Action> 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>() {}

useEffect / useLayoutEffect

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;
}

useRef

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.

Option 1: DOM element ref

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<HTMLDivElement>
  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}>etc</div>;
}

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:

image

Option 2: Mutable value ref

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<number | null>
  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 timer</button>;
}
See also

useImperativeHandle

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>Countdown</div>;
});
// 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} />;
}
See also:

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:

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.

More Hooks + TypeScript reading:

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:

Something to add? File an issue.

Class Components

Within TypeScript, React.Component is a generic type (aka React.Component<PropType, StateType>), 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.

See commentary by @ferdaber here.

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<P,S> 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.

Typing getDerivedStateFromProps

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

  1. 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 {
    //
  }
}
  1. 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) {}
}
  1. 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

You May Not Need defaultProps

As per this tweet, defaultProps will eventually be deprecated. You can check the discussions here:

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} />;

Typing defaultProps

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;

See this in TS Playground

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 overApparentGreetPropsmay be a little intimidating. You can reduce this boilerplate with theComponentProps 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:

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" />;
Solution

Define a utility that applies React.JSX.LibraryManagedAttributes:

type ComponentProps<T> = T extends
  | React.ComponentType<infer P>
  | React.Component<infer P>
  ? React.JSX.LibraryManagedAttributes<T, P>
  : never;

const TestComponent = (props: ComponentProps<typeof GreetComponent>) => {
  return <h1 />;
};

// No error
const el = <TestComponent name="foo" />;

See this in TS Playground

Misc Discussions and Knowledge

Why does React.FC break defaultProps?

You can check the discussions here:

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:

type Props = Required<typeof MyComponent.defaultProps> & {
  /* additional props here */
};

export class MyComponent extends React.Component<Props> {
  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!

interface IMyComponentProps {
  firstProp?: string;
  secondProp: IPerson[];
}

export class MyComponent extends React.Component<IMyComponentProps> {
  public static defaultProps: Partial<IMyComponentProps> = {
    firstProp: "default",
  };
}

The problem with this approach is it causes complex issues with the type inference working with React.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 and here.

Something to add? File an issue.

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:

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";
  /** an object with known properties (but could have more at runtime) */
  obj: {
    id: string;
    title: string;
  };
  /** array of objects! (common) */
  objArr: {
    id: string;
    title: string;
  }[];
  /** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */
  obj2: object;
  /** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */
  obj3: {};
  /** a dict object with any number of properties of the same type */
  dict1: {
    [key: string]: MyTypeHere;
  };
  dict2: Record<string, MyTypeHere>; // equivalent to dict1
  /** function that doesn't take or return anything (VERY COMMON) */
  onClick: () => void;
  /** function with named prop (VERY COMMON) */
  onChange: (id: number) => void;
  /** function type syntax that takes an event (VERY COMMON) */
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  /** alternative function type syntax that takes an event (VERY COMMON) */
  onClick(event: React.MouseEvent<HTMLButtonElement>): void;
  /** any function as long as you don't invoke it (not recommended) */
  onSomething: Function;
  /** an optional prop (VERY COMMON!) */
  optional?: OptionalType;
  /** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */
  setState: React.Dispatch<React.SetStateAction<number>>;
};
object as the non-primitive type

object is a common source of misunderstanding in TypeScript. It does not mean "any object" but rather "any non-primitive type", which means it represents anything that is not number, string, boolean, symbol, null or undefined.

Typing "any non-primitive value" is most likely not something that you should do much in React, which means you will probably not use object much.

Empty interface, {} and Object

An empty interface, {} and Object all represent "any non-nullish value"—not "an empty object" as you might think. Using these types is a common source of misunderstanding and is not recommended.

interface AnyNonNullishValue {} // equivalent to `type AnyNonNullishValue = {}` or `type AnyNonNullishValue = Object`

let value: AnyNonNullishValue;

// these are all fine, but might not be expected
value = 1;
value = "foo";
value = () => alert("foo");
value = {};
value = { foo: "bar" };

// these are errors
value = undefined;
value = null;

Useful React Prop Type Examples

Relevant for components that accept other React components as props.

export declare interface AppProps {
  children?: React.ReactNode; // best, accepts everything React can render
  childrenElement: React.JSX.Element; // A single React element
  style?: React.CSSProperties; // to pass through style props
  onChange?: React.FormEventHandler<HTMLInputElement>; // 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<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref
}
Small React.ReactNode edge case before React 18

Before the React 18 type updates, this code typechecked but had a runtime error:

type Props = {
  children?: React.ReactNode;
};

function Comp({ children }: Props) {
  return <div>{children}</div>;
}
function App() {
  // Before React 18: Runtime error "Objects are not valid as a React child"
  // After React 18: Typecheck error "Type '{}' is not assignable to type 'ReactNode'"
  return <Comp>{{}}</Comp>;
}

This is because ReactNode includes ReactFragment which allowed type {} before React 18.

Thanks @pomle for raising this.

React.JSX.Element vs React.ReactNode?

Quote @ferdaber: 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 React.JSX.Element interface, but React.ReactNode is the set of all possible return values of a component.

  • React.JSX.Element -> Return value of React.createElement
  • React.ReactNode -> Return value of a component

More discussion: Where ReactNode does not overlap with React.JSX.Element

Something to add? File an issue.

Types or Interfaces?

You can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?

TL;DR

Use Interface until You Need Type - orta.

More Advice

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.

The TypeScript Handbook now also includes guidance on Differences Between Type Aliases and Interfaces.

Note: At scale, there are performance reasons to prefer interfaces (see official Microsoft notes on this) but take this with a grain of salt

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)

Something to add? File an issue.

getDerivedStateFromProps

Before you start using getDerivedStateFromProps, please go through the documentation and You Probably Don't Need Derived State. 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.
class Comp extends React.Component<Props, State> {
  static getDerivedStateFromProps(
    props: Props,
    state: State
  ): Partial<State> | null {
    //
  }
}
  1. 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) {}
}
  1. 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

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:

const el = (
  <button
    onClick={(event) => {
      /* event will be correctly typed automatically! */
    }}
  />
);

But if you need to define your event handler separately, IDE tooling really comes in handy here, as the @type definitions come with a wealth of typing. Type what you are looking for and usually the autocomplete will help you out. Here is what it looks like for an onChange for a form event:

type State = {
  text: string;
};
class App extends React.Component<Props, State> {
  state = {
    text: "",
  };

  // typing on RIGHT hand side of =
  onChange = (e: React.FormEvent<HTMLInputElement>): void => {
    this.setState({ text: e.currentTarget.value });
  };
  render() {
    return (
      <div>
        <input type="text" value={this.state.text} onChange={this.onChange} />
      </div>
    );
  }
}

View in the TypeScript Playground

Instead of typing the arguments and return values with React.FormEvent<> and void, you may alternatively apply types to the event handler itself (contributed by @TomasHubelbauer):

  // typing on LEFT hand side of =
  onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
    this.setState({text: e.currentTarget.value})
  }
Why two ways to do the same thing?

The first method uses an inferred method signature (e: React.FormEvent<HTMLInputElement>): void and the second method enforces a type of the delegate provided by @types/react. So React.ChangeEventHandler<> is simply a "blessed" typing by @types/react, whereas you can think of the inferred method as more... artisanally hand-rolled. Either way it's a good pattern to know. See our Github PR for more.

Typing onSubmit, with Uncontrolled components in a Form

If you don't quite care about the type of the event, you can just use React.SyntheticEvent. If your target form has custom named inputs that you'd like to access, you can use a type assertion:

<form
  ref={formRef}
  onSubmit={(e: React.SyntheticEvent) => {
    e.preventDefault();
    const target = e.target as typeof e.target & {
      email: { value: string };
      password: { value: string };
    };
    const email = target.email.value; // typechecks!
    const password = target.password.value; // typechecks!
    // etc...
  }}
>
  <div>
    <label>
      Email:
      <input type="email" name="email" />
    </label>
  </div>
  <div>
    <label>
      Password:
      <input type="password" name="password" />
    </label>
  </div>
  <div>
    <input type="submit" value="Log in" />
  </div>
</form>

View in the TypeScript Playground

Of course, if you're making any sort of significant form, you should use Formik or React Hook Form, which are written in TypeScript.

List of event types
Event Type Description
AnimationEvent CSS Animations.
ChangeEvent Changing the value of <input>, <select> and <textarea> element.
ClipboardEvent Using copy, paste and cut events.
CompositionEvent Events that occur due to the user indirectly entering text (e.g. depending on Browser and PC setup, a popup window may appear with additional characters if you e.g. want to type Japanese on a US Keyboard)
DragEvent Drag and drop interaction with a pointer device (e.g. mouse).
FocusEvent Event that occurs when elements gets or loses focus.
FormEvent Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted.
InvalidEvent Fired when validity restrictions of an input fails (e.g <input type="number" max="10"> and someone would insert number 20).
KeyboardEvent User interaction with the keyboard. Each event describes a single key interaction.
MouseEvent Events that occur due to the user interacting with a pointing device (e.g. mouse)
PointerEvent Events that occur due to user interaction with a variety pointing of devices such as mouse, pen/stylus, a touchscreen and which also supports multi-touch. Unless you develop for older browsers (IE10 or Safari 12), pointer events are recommended. Extends UIEvent.
TouchEvent Events that occur due to the user interacting with a touch device. Extends UIEvent.
TransitionEvent CSS Transition. Not fully browser supported. Extends UIEvent
UIEvent Base Event for Mouse, Touch and Pointer events.
WheelEvent Scrolling on a mouse wheel or similar input device. (Note: wheel event should not be confused with the scroll event)
SyntheticEvent The base event for all above events. Should be used when unsure about event type
What about InputEvent?

You've probably noticed that there is no InputEvent. This is because it is not supported by Typescript as the event itself has no fully browser support and may behave differently in different browsers. You can use KeyboardEvent instead.

Sources:

Context

Basic example

Here's a basic example of creating a context containing the active theme.

import { createContext } from "react";

type ThemeContextType = "light" | "dark";

const ThemeContext = createContext<ThemeContextType>("light");

Wrap the components that need the context with a context provider:

import { useState } from "react";

const App = () => {
  const [theme, setTheme] = useState<ThemeContextType>("light");

  return (
    <ThemeContext.Provider value={theme}>
      <MyComponent />
    </ThemeContext.Provider>
  );
};

Call useContext to read and subscribe to the context.

import { useContext } from "react";

const MyComponent = () => {
  const theme = useContext(ThemeContext);

  return <p>The current theme is {theme}.</p>;
};

Without default context value

If you don't have any meaningful default value, specify null:

import { createContext } from "react";

interface CurrentUserContextType {
  username: string;
}

const CurrentUserContext = createContext<CurrentUserContextType | null>(null);
const App = () => {
  const [currentUser, setCurrentUser] = useState<CurrentUserContextType>({
    username: "filiptammergard",
  });

  return (
    <CurrentUserContext.Provider value={currentUser}>
      <MyComponent />
    </CurrentUserContext.Provider>
  );
};

Now that the type of the context can be null, you'll notice that you'll get a 'currentUser' is possibly 'null' TypeScript error if you try to access the username property. You can use optional chaining to access username:

import { useContext } from "react";

const MyComponent = () => {
  const currentUser = useContext(CurrentUserContext);

  return <p>Name: {currentUser?.username}.</p>;
};

However, it would be preferable to not have to check for null, since we know that the context won't be null. One way to do that is to provide a custom hook to use the context, where an error is thrown if the context is not provided:

import { createContext } from "react";

interface CurrentUserContextType {
  username: string;
}

const CurrentUserContext = createContext<CurrentUserContextType | null>(null);

const useCurrentUser = () => {
  const currentUserContext = useContext(CurrentUserContext);

  if (!currentUserContext) {
    throw new Error(
      "useCurrentUser has to be used within <CurrentUserContext.Provider>"
    );
  }

  return currentUserContext;
};

Using a runtime type check in this will has the benefit of printing a clear error message in the console when a provider is not wrapping the components properly. Now it's possible to access currentUser.username without checking for null:

import { useContext } from "react";

const MyComponent = () => {
  const currentUser = useCurrentUser();

  return <p>Username: {currentUser.username}.</p>;
};
Type assertion as an alternative

Another way to avoid having to check for null is to use type assertion to tell TypeScript you know the context is not null:

import { useContext } from "react";

const MyComponent = () => {
  const currentUser = useContext(CurrentUserContext);

  return <p>Name: {currentUser!.username}.</p>;
};

Another option is to use an empty object as default value and cast it to the expected context type:

const CurrentUserContext = createContext<CurrentUserContextType>(
  {} as CurrentUserContextType
);

You can also use non-null assertion to get the same result:

const CurrentUserContext = createContext<CurrentUserContextType>(null!);

When you don't know what to choose, prefer runtime checking and throwing over type asserting.

forwardRef/createRef

Check the Hooks section for useRef.

createRef:

import { createRef, PureComponent } from "react";

class CssThemeProvider extends PureComponent<Props> {
  private rootRef = createRef<HTMLDivElement>(); // like this
  render() {
    return <div ref={this.rootRef}>{this.props.children}</div>;
  }
}

forwardRef:

import { forwardRef, ReactNode } from "react";

interface Props {
  children?: ReactNode;
  type: "submit" | "button";
}
export type Ref = HTMLButtonElement;

export const FancyButton = forwardRef<Ref, Props>((props, ref) => (
  <button ref={ref} className="MyClassName" type={props.type}>
    {props.children}
  </button>
));
Side note: the ref you get from forwardRef is mutable so you can assign to it if needed.

This was done on purpose. You can make it immutable if you have to - assign React.Ref if you want to ensure nobody reassigns it:

import { forwardRef, ReactNode, Ref } from "react";

interface Props {
  children?: ReactNode;
  type: "submit" | "button";
}

export const FancyButton = forwardRef(
  (
    props: Props,
    ref: Ref<HTMLButtonElement> // <-- here!
  ) => (
    <button ref={ref} className="MyClassName" type={props.type}>
      {props.children}
    </button>
  )
);

If you are grabbing the props of a component that forwards refs, use ComponentPropsWithRef.

Generic forwardRefs

Read more context in https://fettblog.eu/typescript-react-generic-forward-refs/:

Option 1 - Wrapper component
type ClickableListProps<T> = {
  items: T[];
  onSelect: (item: T) => void;
  mRef?: React.Ref<HTMLUListElement> | null;
};

export function ClickableList<T>(props: ClickableListProps<T>) {
  return (
    <ul ref={props.mRef}>
      {props.items.map((item, i) => (
        <li key={i}>
          <button onClick={(el) => props.onSelect(item)}>Select</button>
          {item}
        </li>
      ))}
    </ul>
  );
}
Option 2 - Redeclare forwardRef
// Redeclare forwardRef
declare module "react" {
  function forwardRef<T, P = {}>(
    render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
  ): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
}

// Just write your components like you're used to!
import { forwardRef, ForwardedRef } from "react";

interface ClickableListProps<T> {
  items: T[];
  onSelect: (item: T) => void;
}

function ClickableListInner<T>(
  props: ClickableListProps<T>,
  ref: ForwardedRef<HTMLUListElement>
) {
  return (
    <ul ref={ref}>
      {props.items.map((item, i) => (
        <li key={i}>
          <button onClick={(el) => props.onSelect(item)}>Select</button>
          {item}
        </li>
      ))}
    </ul>
  );
}

export const ClickableList = forwardRef(ClickableListInner);

More Info

You may also wish to do Conditional Rendering with forwardRef.

Something to add? File an issue.

Portals

Using ReactDOM.createPortal:

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<{ children?: React.ReactNode }> {
  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

Using hooks

Same as above but using hooks

import { useEffect, useRef, ReactNode } from "react";
import { createPortal } from "react-dom";

const modalRoot = document.querySelector("#modal-root") as HTMLElement;

type ModalProps = {
  children: ReactNode;
};

function Modal({ children }: ModalProps) {
  // create div element only once using ref
  const elRef = useRef<HTMLDivElement | null>(null);
  if (!elRef.current) elRef.current = document.createElement("div");

  useEffect(() => {
    const el = elRef.current!; // non-null assertion because it will never be null
    modalRoot.appendChild(el);
    return () => {
      modalRoot.removeChild(el);
    };
  }, []);

  return createPortal(children, elRef.current);
}

View in the TypeScript Playground

Modal Component Usage Example:

import { useState } from "react";

function App() {
  const [showModal, setShowModal] = useState(false);

  return (
    <div>
      // you can also put this in your static html file
      <div id="modal-root"></div>
      {showModal && (
        <Modal>
          <div
            style={{
              display: "grid",
              placeItems: "center",
              height: "100vh",
              width: "100vh",
              background: "rgba(0,0,0,0.1)",
              zIndex: 99,
            }}
          >
            I'm a modal!{" "}
            <button
              style={{ background: "papyawhip" }}
              onClick={() => setShowModal(false)}
            >
              close
            </button>
          </div>
        </Modal>
      )}
      <button onClick={() => setShowModal(true)}>show Modal</button>
      // rest of your app
    </div>
  );
}
Context of Example

This example is based on the Event Bubbling Through Portal example of React docs.

Error Boundaries

Option 1: Using react-error-boundary

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.

Option 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.

import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children?: ReactNode;
}

interface State {
  hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
  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 <h1>Sorry.. there was an error</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Something to add? File an issue.

Concurrent React/React Suspense

Not written yet. watch https://github.com/sw-yx/fresh-async-react for more on React Suspense and Time Slicing.

Something to add? File an issue.

Troubleshooting Handbook: Types

⚠️ Have you read the TypeScript 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:

class App extends React.Component<
  {},
  {
    count: number | null; // like this
  }
> {
  state = {
    count: null,
  };
  render() {
    return <div onClick={() => this.increment(1)}>{this.state.count}</div>;
  }
  increment = (amt: number) => {
    this.setState((state) => ({
      count: (state.count || 0) + amt,
    }));
  };
}

View in the TypeScript Playground

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:

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

Method 2 is also known as 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 if you need help. (See also: Basarat's writeup). 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).

class MyComponent extends React.Component<{
  message?: string; // like this
}> {
  render() {
    const { message = "default" } = this.props;
    return <div>{message}</div>;
  }
}

You can also use a ! character to assert that something is not undefined, but this is not encouraged.

Something to add? File an issue with your suggestions!

Enum Types

We recommend avoiding using enums as far as possible.

Enums have a few documented issues (the TS team agrees). A simpler alternative to enums is just declaring a union type of string literals:

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:

export enum ButtonSizes {
  default = "default",
  small = "small",
  large = "large",
}

// usage
export const PrimaryButton = (
  props: Props & React.HTMLProps<HTMLButtonElement>
) => <Button size={ButtonSizes.default} {...props} />;

Type Assertion

Sometimes you know better than TypeScript that the type you're using is narrower than it thinks, or union types need to be asserted to a more specific type to work with other APIs, so assert with the as keyword. This tells the compiler you know better than it does.

class MyComponent extends React.Component<{
  message: string;
}> {
  render() {
    const { message } = this.props;
    return (
      <Component2 message={message as SpecialMessageType}>{message}</Component2>
    );
  }
}

View in the TypeScript Playground

Note that you cannot assert your way to anything - basically it is only for refining types. Therefore it is not the same as "casting" a type.

You can also assert a property is non-null, when accessing it:

element.parentNode!.removeChild(element); // ! before the period
myFunction(document.getElementById(dialog.id!)!); // ! after the property accessing
let userID!: string; // definite assignment assertion... be careful!

Of course, try to actually handle the null case instead of asserting :)

Simulating Nominal Types

TS' structural typing is handy, until it is inconvenient. However you can simulate nominal typing with type branding:

type OrderID = string & { readonly brand: unique symbol };
type UserID = string & { readonly brand: unique symbol };
type ID = OrderID | UserID;

We can create these values with the Companion Object Pattern:

function OrderID(id: string) {
  return id as OrderID;
}
function UserID(id: string) {
  return id as UserID;
}

Now TypeScript will disallow you from using the wrong ID in the wrong place:

function queryForUser(id: UserID) {
  // ...
}
queryForUser(OrderID("foobar")); // Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'

In future you can use the unique keyword to brand. See this PR.

Intersection Types

Adding two types together can be handy, for example when your component is supposed to mirror the props of a native component like a button:

export interface PrimaryButtonProps {
  label: string;
}
export const PrimaryButton = (
  props: PrimaryButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>
) => {
  // do custom buttony stuff
  return <button {...props}> {props.label} </button>;
};

Playground here

You can also use Intersection Types to make reusable subsets of props for similar components:

type BaseProps = {
   className?: string,
   style?: React.CSSProperties
   name: string // used in both
}
type DogProps = {
  tailsCount: number
}
type HumanProps = {
  handsCount: number
}
export const Human = (props: BaseProps & HumanProps) => // ...
export const Dog = (props: BaseProps & DogProps) => // ...

View in the TypeScript Playground

Make sure not to confuse Intersection Types (which are and operations) with Union Types (which are or operations).

Union Types

This section is yet to be written (please contribute!). Meanwhile, see our commentary on Union Types usecases.

The ADVANCED cheatsheet also has information on Discriminated Union Types, which are helpful when TypeScript doesn't seem to be narrowing your union type as you expect.

Overloading Function Types

Specifically when it comes to functions, you may need to overload instead of union type. The most common way function types are written uses the shorthand:

type FunctionType1 = (x: string, y: number) => number;

But this doesn't let you do any overloading. If you have the implementation, you can put them after each other with the function keyword:

function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
function pickCard(x): any {
  // implementation with combined signature
  // ...
}

However, if you don't have an implementation and are just writing a .d.ts definition file, this won't help you either. In this case you can forego any shorthand and write them the old-school way. The key thing to remember here is as far as TypeScript is concerned, functions are just callable objects with no key:

type pickCard = {
  (x: { suit: string; card: number }[]): number;
  (x: number): { suit: string; card: number };
  // no need for combined signature in this form
  // you can also type static properties of functions here eg `pickCard.wasCalled`
};

Note that when you implement the actual overloaded function, the implementation will need to declare the combined call signature that you'll be handling, it won't be inferred for you. You can readily see examples of overloads in DOM APIs, e.g. createElement.

Read more about Overloading in the Handbook.

Using Inferred Types

Leaning on TypeScript's Type Inference is great... until you realize you need a type that was inferred, and have to go back and explicitly declare types/interfaces so you can export them for reuse.

Fortunately, with typeof, you won't have to do that. Just use it on any value:

const [state, setState] = useState({
  foo: 1,
  bar: 2,
}); // state's type inferred to be {foo: number, bar: number}

const someMethod = (obj: typeof state) => {
  // grabbing the type of state even though it was inferred
  // some code using obj
  setState(obj); // this works
};

Using Partial Types

Working with slicing state and props is common in React. Again, you don't really have to go and explicitly redefine your types if you use the Partial generic type:

const [state, setState] = useState({
  foo: 1,
  bar: 2,
}); // state's type inferred to be {foo: number, bar: number}

// NOTE: stale state merging is not actually encouraged in useState
// we are just demonstrating how to use Partial here
const partialStateUpdate = (obj: Partial<typeof state>) =>
  setState({ ...state, ...obj });

// later on...
partialStateUpdate({ foo: 2 }); // this works
Minor caveats on using Partial

Note that there are some TS users who don't agree with using Partial as it behaves today. See subtle pitfalls of the above example here, and check out this long discussion on why @types/react uses Pick instead of Partial.

The Types I need weren't exported!

This can be annoying but here are ways to grab the types!

  • Grabbing the Prop types of a component: Use React.ComponentProps and typeof, and optionally Omit any overlapping types
import { Button } from "library"; // but doesn't export ButtonProps! oh no!
type ButtonProps = React.ComponentProps<typeof Button>; // no problem! grab your own!
type AlertButtonProps = Omit<ButtonProps, "onClick">; // modify
const AlertButton = (props: AlertButtonProps) => (
  <Button onClick={() => alert("hello")} {...props} />
);

You may also use ComponentPropsWithoutRef (instead of ComponentProps) and ComponentPropsWithRef (if your component specifically forwards refs)

  • Grabbing the return type of a function: use ReturnType:
// inside some library - return type { baz: number } is inferred but not exported
function foo(bar: string) {
  return { baz: 1 };
}

//  inside your app, if you need { baz: number }
type FooReturn = ReturnType<typeof foo>; // { baz: number }

In fact you can grab virtually anything public: see this blogpost from Ivan Koshelev

function foo() {
  return {
    a: 1,
    b: 2,
    subInstArr: [
      {
        c: 3,
        d: 4,
      },
    ],
  };
}

type InstType = ReturnType<typeof foo>;
type SubInstArr = InstType["subInstArr"];
type SubInstType = SubInstArr[0];

let baz: SubInstType = {
  c: 5,
  d: 6, // type checks ok!
};

//You could just write a one-liner,
//But please make sure it is forward-readable
//(you can understand it from reading once left-to-right with no jumps)
type SubInstType2 = ReturnType<typeof foo>["subInstArr"][0];
let baz2: SubInstType2 = {
  c: 5,
  d: 6, // type checks ok!
};
  • TS also ships with a Parameters utility type for extracting the parameters of a function
  • for anything more "custom", the infer keyword is the basic building block for this, but takes a bit of getting used to. Look at the source code for the above utility types, and this example to get the idea. Basarat also has a good video on infer.

The Types I need don't exist!

What's more annoying than modules with unexported types? Modules that are untyped!

Before you proceed - make sure you have checked that types don't exist in DefinitelyTyped or TypeSearch

Fret not! There are more than a couple of ways in which you can solve this problem.

Slapping any on everything

A lazier way would be to create a new type declaration file, say typedec.d.ts– if you don't already have one. Ensure that the path to file is resolvable by TypeScript by checking the include array in the tsconfig.json file at the root of your directory.

// inside tsconfig.json
{
  // ...
  "include": [
    "src" // automatically resolves if the path to declaration is src/typedec.d.ts
  ]
  // ...
}

Within this file, add the declare syntax for your desired module, say my-untyped-module– to the declaration file:

// inside typedec.d.ts
declare module "my-untyped-module";

This one-liner alone is enough if you just need it to work without errors. A even hackier, write-once-and-forget way would be to use "*" instead which would then apply the Any type for all existing and future untyped modules.

This solution works well as a workaround if you have less than a couple untyped modules. Anything more, you now have a ticking type-bomb in your hands. The only way of circumventing this problem would be to define the missing types for those untyped modules as explained in the following sections.

Autogenerate types

You can use TypeScript with --allowJs and --declaration to see TypeScript's "best guess" at the types of the library.

If this doesn't work well enough, use dts-gen to use the runtime shape of the object to accurately enumerate all available properties. This tends to be very accurate, BUT the tool does not yet support scraping JSDoc comments to populate additional types.

npm install -g dts-gen
dts-gen -m <your-module>

There are other automated JS to TS conversion tools and migration strategies - see our MIGRATION cheatsheet.

Typing Exported Hooks

Typing Hooks is just like typing pure functions.

The following steps work under two assumptions:

  • You have already created a type declaration file as stated earlier in the section.
  • You have access to the source code - specifically the code that directly exports the functions you will be using. In most cases, it would be housed in an index.js file. Typically you need a minimum of two type declarations (one for Input Prop and the other for Return Prop) to define a hook completely. Suppose the hook you wish to type follows the following structure,
// ...
const useUntypedHook = (prop) => {
  // some processing happens here
  return {
    /* ReturnProps */
  };
};
export default useUntypedHook;

then, your type declaration should most likely follow the following syntax.

declare module 'use-untyped-hook' {
  export interface InputProps { ... }   // type declaration for prop
  export interface ReturnProps { ... } // type declaration for return props
  export default function useUntypedHook(
    prop: InputProps
    // ...
  ): ReturnProps;
}
For instance, the useDarkMode hook exports the functions that follows a similar structure.
// inside src/index.js
const useDarkMode = (
  initialValue = false, // -> input props / config props to be exported
  {
    // -> input props / config props to be exported
    element,
    classNameDark,
    classNameLight,
    onChange,
    storageKey = "darkMode",
    storageProvider,
    global,
  } = {}
) => {
  // ...
  return {
    // -> return props to be exported
    value: state,
    enable: useCallback(() => setState(true), [setState]),
    disable: useCallback(() => setState(false), [setState]),
    toggle: useCallback(() => setState((current) => !current), [setState]),
  };
};
export default useDarkMode;

As the comments suggest, exporting these config props and return props following the aforementioned structure will result in the following type export.

declare module "use-dark-mode" {
  /**
   * A config object allowing you to specify certain aspects of `useDarkMode`
   */
  export interface DarkModeConfig {
    classNameDark?: string; // A className to set "dark mode". Default = "dark-mode".
    classNameLight?: string; // A className to set "light mode". Default = "light-mode".
    element?: HTMLElement; // The element to apply the className. Default = `document.body`
    onChange?: (val?: boolean) => void; // Override the default className handler with a custom callback.
    storageKey?: string; // Specify the `localStorage` key. Default = "darkMode". Set to `null` to disable persistent storage.
    storageProvider?: WindowLocalStorage; // A storage provider. Default = `localStorage`.
    global?: Window; // The global object. Default = `window`.
  }
  /**
   * An object returned from a call to `useDarkMode`.
   */
  export interface DarkMode {
    readonly value: boolean;
    enable: () => void;
    disable: () => void;
    toggle: () => void;
  }
  /**
   * A custom React Hook to help you implement a "dark mode" component for your application.
   */
  export default function useDarkMode(
    initialState?: boolean,
    config?: DarkModeConfig
  ): DarkMode;
}
Typing Exported Components

In case of typing untyped class components, there's almost no difference in approach except for the fact that after declaring the types, you export the extend the type using class UntypedClassComponent extends React.Component<UntypedClassComponentProps, any> {} where UntypedClassComponentProps holds the type declaration.

For instance, sw-yx's Gist on React Router 6 types implemented a similar method for typing the then untyped RR6.

declare module "react-router-dom" {
  import * as React from 'react';
  // ...
  type NavigateProps<T> = {
    to: string | number,
    replace?: boolean,
    state?: T
  }
  //...
  export class Navigate<T = any> extends React.Component<NavigateProps<T>>{}
  // ...

For more information on creating type definitions for class components, you can refer to this post for reference.

Frequent Known Problems with TypeScript

Just a list of stuff that React developers frequently run into, that TS has no solution for. Not necessarily TSX only.

TypeScript doesn't narrow after an object element null check

https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg&name=medium

Ref: https://mobile.twitter.com/tannerlinsley/status/1390409931627499523. see also microsoft/TypeScript#9998

TypeScript doesn't let you restrict the type of children

Guaranteeing typesafety for this kind of API isn't possible:

<Menu>
  <MenuItem/> {/* ok */}
  <MenuLink/> {/* ok */}
  <div> {/* error */}
</Menu>

Source: https://twitter.com/ryanflorence/status/1085745787982700544?s=20

Troubleshooting Handbook: Operators

  • typeof and instanceof: type query used for refinement
  • keyof: get keys of an object. keyof T is an operator to tell you what values of k can be used for obj[k].
  • O[K]: property lookup
  • [K in O]: mapped types
  • + or - or readonly or ?: addition and subtraction and readonly and optional modifiers
  • x ? Y : Z: Conditional types for generic types, type aliases, function parameter types
  • !: Nonnull assertion for nullable types
  • =: Generic type parameter default for generic types
  • as: type assertion
  • is: type guard for function return types

Conditional Types are a difficult topic to get around so here are some extra resources:

Troubleshooting Handbook: Utilities

These are all built in, see source in es5.d.ts:

  • Awaited: emulate the behavior of await
  • Capitalize: convert first character of string literal type to uppercase
  • ConstructorParameters: a tuple of class constructor's parameter types
  • Exclude: exclude a type from another type
  • Extract: select a subtype that is assignable to another type
  • InstanceType: the instance type you get from a newing a class constructor
  • Lowercase: convert string literal type to lowercase
  • NonNullable: exclude null and undefined from a type
  • Omit: construct a type with the properties of another type.
  • OmitThisParameter: remove the 'this' parameter from a function type.
  • Parameters: a tuple of a function's parameter types
  • Partial: Make all properties in an object optional
  • Readonly: Make all properties in an object readonly
  • ReadonlyArray: Make an immutable array of the given type
  • Pick: A subtype of an object type with a subset of its keys
  • Record: A map from a key type to a value type
  • Required: Make all properties in an object required
  • ReturnType: A function's return type
  • ThisParameterType: extract the type of the 'this' parameter of a function type
  • ThisType: marker for contextual 'this' type
  • Uncapitalize: convert first character of string literal type to lowercase
  • Uppercase: convert string literal type to uppercase

Troubleshooting Handbook: tsconfig.json

You can find all the Compiler options in the TypeScript docs. The new TS docs also has per-flag annotations of what each does. This is the setup I roll with for APPS (not libraries - for libraries you may wish to see the settings we use in tsdx):

{
  "compilerOptions": {
    "incremental": true,
    "outDir": "build/lib",
    "target": "es5",
    "module": "esnext",
    "lib": ["DOM", "ESNext"],
    "sourceMap": true,
    "importHelpers": true,
    "declaration": true,
    "rootDir": "src",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowJs": false,
    "jsx": "react",
    "moduleResolution": "node",
    "baseUrl": "src",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "suppressImplicitAnyIndexErrors": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "build", "scripts"]
}

You can find more recommended TS config here.

Please open an issue and discuss if there are better recommended choices for React.

Selected flags and why we like them:

  • esModuleInterop: disables namespace imports (import * as foo from "foo") and enables CJS/AMD/UMD style imports (import fs from "fs")
  • strict: strictPropertyInitialization forces you to initialize class properties or explicitly declare that they can be undefined. You can opt out of this with a definite assignment assertion.
  • "typeRoots": ["./typings", "./node_modules/@types"]: By default, TypeScript looks in node_modules/@types and parent folders for third party type declarations. You may wish to override this default resolution so you can put all your global type declarations in a special typings folder.

Compilation time grows linearly with size of codebase. For large projects, you will want to use Project References. See our ADVANCED cheatsheet for commentary.

Troubleshooting Handbook: Fixing bugs in official typings

If you run into bugs with your library's official typings, you can copy them locally and tell TypeScript to use your local version using the "paths" field. In your tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "mobx-react": ["../typings/modules/mobx-react"]
    }
  }
}

Thanks to @adamrackis for the tip.

If you just need to add an interface, or add missing members to an existing interface, you don't need to copy the whole typing package. Instead, you can use declaration merging:

// my-typings.ts
declare module "plotly.js" {
  interface PlotlyHTMLElement {
    removeAllListeners(): void;
  }
}

// MyComponent.tsx
import { PlotlyHTMLElement } from "plotly.js";

const f = (e: PlotlyHTMLElement) => {
  e.removeAllListeners();
};

You dont always have to implement the module, you can simply import the module as any for a quick start:

// my-typings.ts
declare module "plotly.js"; // each of its imports are `any`

Because you don't have to explicitly import this, this is known as an ambient module declaration. You can do AMD's in a script-mode .ts file (no imports or exports), or a .d.ts file anywhere in your project.

You can also do ambient variable and ambient type declarations:

// ambient utiltity type
type ToArray<T> = T extends unknown[] ? T : T[];
// ambient variable
declare let process: {
  env: {
    NODE_ENV: "development" | "production";
  };
};
process = {
  env: {
    NODE_ENV: "production",
  },
};

You can see examples of these included in the built in type declarations in the lib field of tsconfig.json

Troubleshooting Handbook: Globals, Images and other non-TS files

Use declaration merging.

If, say, you are using a third party JS script that attaches on to the window global, you can extend Window:

declare global {
  interface Window {
    MyVendorThing: MyVendorType;
  }
}

Likewise if you wish to "import" an image or other non TS/TSX file:

// declaration.d.ts
// anywhere in your project, NOT the same name as any of your .ts/tsx files
declare module "*.png";

// importing in a tsx file
import * as logo from "./logo.png";

Note that tsc cannot bundle these files for you, you will have to use Webpack or Parcel.

Related issue: microsoft/TypeScript-React-Starter#12 and StackOverflow

Editor Tooling and Integration

You are free to use this repo's TSX logo if you wish:

https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png

You may also wish to use alternative logos - jsx-tsx-logos

https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png

Linting

⚠️Note that TSLint is now in maintenance and you should try to use ESLint instead. If you are interested in TSLint tips, please check this PR from @azdanov. The rest of this section just focuses on ESLint. You can convert TSlint to ESlint with this tool.

⚠️This is an evolving topic. typescript-eslint-parser is no longer maintained and work has recently begun on typescript-eslint in the ESLint community to bring ESLint up to full parity and interop with TSLint.

Follow the TypeScript + ESLint docs at https://github.com/typescript-eslint/typescript-eslint:

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint

add a lint script to your package.json:

  "scripts": {
    "lint": "eslint 'src/**/*.ts'"
  },

and a suitable .eslintrc.js (using .js over .json here so we can add comments):

module.exports = {
  env: {
    es6: true,
    node: true,
    jest: true,
  },
  extends: "eslint:recommended",
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint"],
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: "module",
  },
  rules: {
    indent: ["error", 2],
    "linebreak-style": ["error", "unix"],
    quotes: ["error", "single"],
    "no-console": "warn",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": [
      "error",
      { vars: "all", args: "after-used", ignoreRestSiblings: false },
    ],
    "@typescript-eslint/explicit-function-return-type": "warn", // Consider using explicit annotations for object literals and function return types even when they can be inferred.
    "no-empty": "warn",
  },
};

Most of this is taken from the tsdx PR which is for libraries.

More .eslintrc.json options to consider with more options you may want for apps:

{
  "extends": [
    "airbnb",
    "prettier",
    "prettier/react",
    "plugin:prettier/recommended",
    "plugin:jest/recommended",
    "plugin:unicorn/recommended"
  ],
  "plugins": ["prettier", "jest", "unicorn"],
  "parserOptions": {
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "es6": true,
    "browser": true,
    "jest": true
  },
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  },
  "overrides": [
    {
      "files": ["**/*.ts", "**/*.tsx"],
      "parser": "typescript-eslint-parser",
      "rules": {
        "no-undef": "off"
      }
    }
  ]
}

Another great resource is "Using ESLint and Prettier in a TypeScript Project" by @robertcoopercode.

Wes Bos is also working on TypeScript support for his eslint+prettier config.

If you're looking for information on Prettier, check out the Prettier guide.

Other React + TypeScript resources

Recommended React + TypeScript talks

Time to Really Learn TypeScript

Believe it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.

There is a whole world of generic type logic that you will eventually get into, however it becomes far less dealing with React than just getting good at TypeScript so it is out of scope here. But at least you can get productive in React now :)

It is worth mentioning some resources to help you get started:

Example App

My question isn't answered here!

Contributors

This project follows the all-contributors specification. See CONTRIBUTORS.md for the full list. Contributions of any kind welcome!

typescript-cheatsheets/react

{
"props": {
"initialPayload": {
"allShortcutsEnabled": false,
"path": "/",
"repo": {
"id": 135786093,
"defaultBranch": "main",
"name": "react",
"ownerLogin": "typescript-cheatsheets",
"currentUserCanPush": false,
"isFork": false,
"isEmpty": false,
"createdAt": "2018-06-02T04:08:16.000Z",
"ownerAvatar": "https://avatars.githubusercontent.com/u/50188264?v=4",
"public": true,
"private": false,
"isOrgOwned": true
},
"currentUser": null,
"refInfo": {
"name": "main",
"listCacheKey": "v0:1707317872.0",
"canEdit": false,
"refType": "branch",
"currentOid": "4d6be66572c9544cf55d4ce86cddf63569db269b"
},
"tree": {
"items": [
{
"name": ".github",
"path": ".github",
"contentType": "directory"
},
{
"name": ".husky",
"path": ".husky",
"contentType": "directory"
},
{
"name": "docs",
"path": "docs",
"contentType": "directory"
},
{
"name": "website",
"path": "website",
"contentType": "directory"
},
{
"name": ".all-contributorsrc",
"path": ".all-contributorsrc",
"contentType": "file"
},
{
"name": ".dockerignore",
"path": ".dockerignore",
"contentType": "file"
},
{
"name": ".gitignore",
"path": ".gitignore",
"contentType": "file"
},
{
"name": ".nvmrc",
"path": ".nvmrc",
"contentType": "file"
},
{
"name": "CONTRIBUTING.md",
"path": "CONTRIBUTING.md",
"contentType": "file"
},
{
"name": "CONTRIBUTORS.md",
"path": "CONTRIBUTORS.md",
"contentType": "file"
},
{
"name": "LICENSE",
"path": "LICENSE",
"contentType": "file"
},
{
"name": "README.md",
"path": "README.md",
"contentType": "file"
},
{
"name": "code-of-conduct.md",
"path": "code-of-conduct.md",
"contentType": "file"
},
{
"name": "copyFile.js",
"path": "copyFile.js",
"contentType": "file"
},
{
"name": "genReadme.js",
"path": "genReadme.js",
"contentType": "file"
},
{
"name": "netlify.toml",
"path": "netlify.toml",
"contentType": "file"
},
{
"name": "package.json",
"path": "package.json",
"contentType": "file"
},
{
"name": "yarn.lock",
"path": "yarn.lock",
"contentType": "file"
}
],
"templateDirectorySuggestionUrl": null,
"readme": null,
"totalCount": 18,
"showBranchInfobar": false
},
"fileTree": null,
"fileTreeProcessingTime": null,
"foldersToFetch": [],
"treeExpanded": false,
"symbolsExpanded": false,
"isOverview": true,
"overview": {
"banners": {
"shouldRecommendReadme": false,
"isPersonalRepo": false,
"showUseActionBanner": false,
"actionSlug": null,
"actionId": null,
"showProtectBranchBanner": false,
"recentlyTouchedDataChannel": null,
"publishBannersInfo": {
"dismissActionNoticePath": "/settings/dismiss-notice/publish_action_from_repo",
"releasePath": "/typescript-cheatsheets/react/releases/new?marketplace=true",
"showPublishActionBanner": false
},
"interactionLimitBanner": null,
"showInvitationBanner": false,
"inviterName": null
},
"codeButton": {
"contactPath": "/contact",
"isEnterprise": false,
"local": {
"protocolInfo": {
"httpAvailable": true,
"sshAvailable": null,
"httpUrl": "https://github.com/typescript-cheatsheets/react.git",
"showCloneWarning": null,
"sshUrl": null,
"sshCertificatesRequired": null,
"sshCertificatesAvailable": null,
"ghCliUrl": "gh repo clone typescript-cheatsheets/react",
"defaultProtocol": "http",
"newSshKeyUrl": "/settings/ssh/new",
"setProtocolPath": "/users/set_protocol"
},
"platformInfo": {
"cloneUrl": "https://desktop.github.com",
"showVisualStudioCloneButton": false,
"visualStudioCloneUrl": "https://windows.github.com",
"showXcodeCloneButton": false,
"xcodeCloneUrl": "https://developer.apple.com",
"zipballUrl": "/typescript-cheatsheets/react/archive/refs/heads/main.zip"
}
},
"newCodespacePath": "/codespaces/new?hide_repo_select=true&repo=135786093"
},
"popovers": {
"rename": null,
"renamedParentRepo": null
},
"commitCount": "1,034",
"overviewFiles": [
{
"displayName": "README.md",
"repoName": "react",
"refName": "main",
"path": "README.md",
"preferredFileType": "readme",
"tabName": "README",
"richText": "<article class=\"markdown-body entry-content container-lg\" itemprop=\"text\"><h1 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-reacttypescript-cheatsheets\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#reacttypescript-cheatsheets\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>React+TypeScript Cheatsheets</h1>\n<p dir=\"auto\">Cheatsheets for experienced React developers getting started with TypeScript</p>\n<hr>\n<a href=\"https://github.com/typescript-cheatsheets/react/issues/81\" data-hovercard-type=\"issue\" data-hovercard-url=\"/typescript-cheatsheets/react/issues/81/hovercard\">\n <img height=\"90\" width=\"90\" alt=\"react + ts logo\" src=\"https://user-images.githubusercontent.com/84442212/194379444-02e5ec69-5e6c-4100-bd7a-c31d628af29c.png\" align=\"left\" style=\"max-width: 100%;\">\n</a>\n<p dir=\"auto\"><a href=\"https://react-typescript-cheatsheet.netlify.app/docs/basic/setup\" rel=\"nofollow\"><strong>Web docs</strong></a> |\n<a href=\"https://github.com/typescript-cheatsheets/react-typescript-cheatsheet-es\"><strong>Español</strong></a> |\n<a href=\"https://github.com/typescript-cheatsheets/react-pt\"><strong>Português</strong></a> |\n<a href=\"https://github.com/typescript-cheatsheets/react/blob/main/CONTRIBUTING.md\">Contribute!</a> |\n<a href=\"https://github.com/typescript-cheatsheets/react/issues/new/choose\">Ask!</a></p>\n<p dir=\"auto\">👋 This repo is maintained by <a href=\"https://twitter.com/swyx\" rel=\"nofollow\">@swyx</a>, <a href=\"https://twitter.com/sebsilbermann\" rel=\"nofollow\">@eps1lon</a> and <a href=\"https://twitter.com/tammergard\" rel=\"nofollow\">@filiptammergard</a>. We're so happy you want to try out TypeScript with React! If you see anything wrong or missing, please <a href=\"https://github.com/typescript-cheatsheets/react/issues/new/choose\">file an issue</a>! 👍</p>\n<hr>\n<p dir=\"auto\"><a href=\"/typescript-cheatsheets/react/blob/main/CONTRIBUTORS.md\"><img src=\"https://camo.githubusercontent.com/e896bdf810b74ca94a0b0316128b0a9081bd11dcda6c1567c837df274166a106/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f636f6e7472696275746f72732f747970657363726970742d63686561747368656574732f72656163742d747970657363726970742d636865617473686565743f636f6c6f723d6f72616e6765267374796c653d666c61742d737175617265\" alt=\"All Contributors\" data-canonical-src=\"https://img.shields.io/github/contributors/typescript-cheatsheets/react-typescript-cheatsheet?color=orange&amp;style=flat-square\" style=\"max-width: 100%;\"></a> | <a href=\"https://discord.gg/wTGS5z9\" rel=\"nofollow\"><img src=\"https://camo.githubusercontent.com/75d2ea568a825d36562b24490caf2f929b1d2bcaa74012da2672ea4701323e94/68747470733a2f2f696d672e736869656c64732e696f2f646973636f72642f3530383335373234383333303736303234332e7376673f6c6162656c3d266c6f676f3d646973636f7264266c6f676f436f6c6f723d66666666666626636f6c6f723d373338394438266c6162656c436f6c6f723d364137454332\" alt=\"Discord\" data-canonical-src=\"https://img.shields.io/discord/508357248330760243.svg?label=&amp;logo=discord&amp;logoColor=ffffff&amp;color=7389D8&amp;labelColor=6A7EC2\" style=\"max-width: 100%;\"></a> | <a href=\"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\" rel=\"nofollow\"><img src=\"https://camo.githubusercontent.com/9c61460433a9f326147486342f60949468c81f7dac845c58b1e8f24729f41618/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f75726c3f6c6162656c3d48656c70253230737072656164253230746865253230776f7264253231267374796c653d736f6369616c2675726c3d68747470732533412532462532466769746875622e636f6d253246747970657363726970742d63686561747368656574732532467265616374\" alt=\"Tweet\" data-canonical-src=\"https://img.shields.io/twitter/url?label=Help%20spread%20the%20word%21&amp;style=social&amp;url=https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact\" style=\"max-width: 100%;\"></a></p>\n<h2 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-all-react--typescript-cheatsheets\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#all-react--typescript-cheatsheets\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>All React + TypeScript Cheatsheets</h2>\n<ul dir=\"auto\">\n<li><a href=\"https://react-typescript-cheatsheet.netlify.app/docs/basic/setup\" rel=\"nofollow\">The Basic Cheatsheet</a> is focused on helping React devs just start using TS in React <strong>apps</strong>\n<ul dir=\"auto\">\n<li>Focus on opinionated best practices, copy+pastable examples.</li>\n<li>Explains some basic TS types usage and setup along the way.</li>\n<li>Answers the most Frequently Asked Questions.</li>\n<li>Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies.</li>\n<li>The goal is to get effective with TS without learning <em>too much</em> TS.</li>\n</ul>\n</li>\n<li><a href=\"https://react-typescript-cheatsheet.netlify.app/docs/advanced\" rel=\"nofollow\">The Advanced Cheatsheet</a> helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React <strong>libraries</strong>.\n<ul dir=\"auto\">\n<li>It also has miscellaneous tips and tricks for pro users.</li>\n<li>Advice for contributing to DefinitelyTyped.</li>\n<li>The goal is to take <em>full advantage</em> of TypeScript.</li>\n</ul>\n</li>\n<li><a href=\"https://react-typescript-cheatsheet.netlify.app/docs/migration\" rel=\"nofollow\">The Migrating Cheatsheet</a> helps collate advice for incrementally migrating large codebases from JS or Flow, <strong>from people who have done it</strong>.\n<ul dir=\"auto\">\n<li>We do not try to convince people to switch, only to help people who have already decided.</li>\n<li><g-emoji class=\"g-emoji\" alias=\"warning\">⚠️</g-emoji>This is a new cheatsheet, all assistance is welcome.</li>\n</ul>\n</li>\n<li><a href=\"https://react-typescript-cheatsheet.netlify.app/docs/hoc\" rel=\"nofollow\">The HOC Cheatsheet</a>) specifically teaches people to write HOCs with examples.\n<ul dir=\"auto\">\n<li>Familiarity with <a href=\"https://www.typescriptlang.org/docs/handbook/2/generics.html\" rel=\"nofollow\">Generics</a> is necessary.</li>\n<li><g-emoji class=\"g-emoji\" alias=\"warning\">⚠️</g-emoji>This is the newest cheatsheet, all assistance is welcome.</li>\n</ul>\n</li>\n</ul>\n<hr>\n<h2 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-basic-cheatsheet\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#basic-cheatsheet\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Basic Cheatsheet</h2>\n<h3 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-basic-cheatsheet-table-of-contents\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#basic-cheatsheet-table-of-contents\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Basic Cheatsheet Table of Contents</h3>\n<details>\n<summary><b>Expand Table of Contents</b></summary>\n<ul dir=\"auto\">\n<li>\n<p dir=\"auto\"><a href=\"#section-1-setup-typescript-with-react\">Section 1: Setup TypeScript with React</a></p>\n\n<ul dir=\"auto\">\n<li><a href=\"#prerequisites\">Prerequisites</a></li>\n<li><a href=\"#react-and-typescript-starter-kits\">React and TypeScript starter kits</a></li>\n<li><a href=\"#try-react-and-typescript-online\">Try React and TypeScript online</a></li>\n</ul>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#section-2-getting-started\">Section 2: Getting Started</a></p>\n<ul dir=\"auto\">\n<li><a href=\"#function-components\">Function Components</a></li>\n<li><a href=\"#hooks\">Hooks</a></li>\n<li><a href=\"#usestate\">useState</a></li>\n<li><a href=\"#usereducer\">useReducer</a></li>\n<li><a href=\"#useeffect--uselayouteffect\">useEffect / useLayoutEffect</a></li>\n<li><a href=\"#useref\">useRef</a>\n<ul dir=\"auto\">\n<li><a href=\"#option-1-dom-element-ref\">Option 1: DOM element ref</a></li>\n<li><a href=\"#option-2-mutable-value-ref\">Option 2: Mutable value ref</a></li>\n<li><a href=\"#see-also\">See also</a></li>\n</ul>\n</li>\n<li><a href=\"#useimperativehandle\">useImperativeHandle</a></li>\n<li><a href=\"#custom-hooks\">Custom Hooks</a></li>\n<li><a href=\"#more-hooks--typescript-reading\">More Hooks + TypeScript reading:</a></li>\n<li><a href=\"#example-react-hooks--typescript-libraries\">Example React Hooks + TypeScript Libraries:</a></li>\n<li><a href=\"#class-components\">Class Components</a></li>\n<li><a href=\"#typing-getderivedstatefromprops\">Typing getDerivedStateFromProps</a></li>\n<li><a href=\"#you-may-not-need-defaultprops\">You May Not Need <code>defaultProps</code></a></li>\n<li><a href=\"#typing-defaultprops\">Typing <code>defaultProps</code></a></li>\n<li><a href=\"#consuming-props-of-a-component-with-defaultprops\">Consuming Props of a Component with defaultProps</a>\n<ul dir=\"auto\">\n<li><a href=\"#problem-statement\">Problem Statement</a></li>\n<li><a href=\"#solution\">Solution</a></li>\n</ul>\n</li>\n<li><a href=\"#misc-discussions-and-knowledge\">Misc Discussions and Knowledge</a></li>\n<li><a href=\"#typing-component-props\">Typing Component Props</a></li>\n<li><a href=\"#basic-prop-types-examples\">Basic Prop Types Examples</a></li>\n<li><a href=\"#useful-react-prop-type-examples\">Useful React Prop Type Examples</a></li>\n<li><a href=\"#types-or-interfaces\">Types or Interfaces?</a>\n<ul dir=\"auto\">\n<li><a href=\"#tldr\">TL;DR</a></li>\n<li><a href=\"#more-advice\">More Advice</a></li>\n<li><a href=\"#useful-table-for-types-vs-interfaces\">Useful table for Types vs Interfaces</a></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#getderivedstatefromprops\">getDerivedStateFromProps</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#forms-and-events\">Forms and Events</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#list-of-event-types\">List of event types</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#context\">Context</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#basic-example\">Basic Example</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#extended-example\">Extended Example</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#forwardrefcreateref\">forwardRef/createRef</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#generic-forwardrefs\">Generic forwardRefs</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#option-1---wrapper-component\">Option 1 - Wrapper component</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#option-2---redeclare-forwardref\">Option 2 - Redeclare forwardRef</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#more-info\">More Info</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#portals\">Portals</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#error-boundaries\">Error Boundaries</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#option-1-using-react-error-boundary\">Option 1: Using react-error-boundary</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#options-2-writing-your-custom-error-boundary-component\">Options 2: Writing your custom error boundary component</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#concurrent-reactreact-suspense\">Concurrent React/React Suspense</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#troubleshooting-handbook-types\">Troubleshooting Handbook: Types</a></p>\n\n<ul dir=\"auto\">\n<li><a href=\"#union-types-and-type-guarding\">Union Types and Type Guarding</a></li>\n<li><a href=\"#optional-types\">Optional Types</a></li>\n<li><a href=\"#enum-types\">Enum Types</a></li>\n<li><a href=\"#type-assertion\">Type Assertion</a></li>\n<li><a href=\"#simulating-nominal-types\">Simulating Nominal Types</a></li>\n<li><a href=\"#intersection-types\">Intersection Types</a></li>\n<li><a href=\"#union-types\">Union Types</a></li>\n<li><a href=\"#overloading-function-types\">Overloading Function Types</a></li>\n<li><a href=\"#using-inferred-types\">Using Inferred Types</a></li>\n<li><a href=\"#using-partial-types\">Using Partial Types</a></li>\n<li><a href=\"#the-types-i-need-werent-exported\">The Types I need weren't exported!</a></li>\n<li><a href=\"#the-types-i-need-dont-exist\">The Types I need don't exist!</a>\n<ul dir=\"auto\">\n<li><a href=\"#slapping-any-on-everything\">Slapping <code>any</code> on everything</a></li>\n<li><a href=\"#autogenerate-types\">Autogenerate types</a></li>\n<li><a href=\"#typing-exported-hooks\">Typing Exported Hooks</a></li>\n<li><a href=\"#typing-exported-components\">Typing Exported Components</a></li>\n</ul>\n</li>\n<li><a href=\"#frequent-known-problems-with-typescript\">Frequent Known Problems with TypeScript</a>\n<ul dir=\"auto\">\n<li><a href=\"#typescript-doesnt-narrow-after-an-object-element-null-check\">TypeScript doesn't narrow after an object element null check</a></li>\n<li><a href=\"#typescript-doesnt-let-you-restrict-the-type-of-children\">TypeScript doesn't let you restrict the type of children</a></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#troubleshooting-handbook-operators\">Troubleshooting Handbook: Operators</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#troubleshooting-handbook-utilities\">Troubleshooting Handbook: Utilities</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#troubleshooting-handbook-tsconfigjson\">Troubleshooting Handbook: tsconfig.json</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#troubleshooting-handbook-fixing-bugs-in-official-typings\">Troubleshooting Handbook: Fixing bugs in official typings</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#troubleshooting-handbook-globals-images-and-other-non-ts-files\">Troubleshooting Handbook: Globals, Images and other non-TS files</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#editor-tooling-and-integration\">Editor Tooling and Integration</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#linting\">Linting</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#other-react--typescript-resources\">Other React + TypeScript resources</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#recommended-react--typescript-talks\">Recommended React + TypeScript talks</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#time-to-really-learn-typescript\">Time to Really Learn TypeScript</a></p>\n</li>\n<li>\n<p dir=\"auto\"><a href=\"#example-app\">Example App</a></p>\n </li></ul></details>\n\n\n\n<h3 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-section-1-setup\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#section-1-setup\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Section 1: Setup</h3>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-prerequisites\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#prerequisites\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Prerequisites</h4>\n<p dir=\"auto\">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:</p>\n<ul dir=\"auto\">\n<li>Basic understanding of <a href=\"https://react.dev/\" rel=\"nofollow\">React</a>.</li>\n<li>Familiarity with <a href=\"https://www.typescriptlang.org/docs/handbook/2/basic-types.html\" rel=\"nofollow\">TypeScript Basics</a> and <a href=\"https://www.typescriptlang.org/docs/handbook/2/everyday-types.html\" rel=\"nofollow\">Everyday Types</a>.</li>\n</ul>\n<p dir=\"auto\">In the cheatsheet we assume you are using the latest versions of React and TypeScript.</p>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-react-and-typescript-starter-kits\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#react-and-typescript-starter-kits\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>React and TypeScript starter kits</h4>\n<p dir=\"auto\">React has documentation for <a href=\"https://react.dev/learn/start-a-new-react-project\" rel=\"nofollow\">how to start a new React project</a> with some of the most popular frameworks. Here's how to start them with TypeScript:</p>\n<ul dir=\"auto\">\n<li><a href=\"https://nextjs.org/docs/basic-features/typescript\" rel=\"nofollow\">Next.js</a>: <code>npx create-next-app@latest --ts</code></li>\n<li><a href=\"https://remix.run/docs/tutorials/blog\" rel=\"nofollow\">Remix</a>: <code>npx create-remix@latest</code></li>\n<li><a href=\"https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/\" rel=\"nofollow\">Gatsby</a>: <code>npm init gatsby --ts</code></li>\n<li><a href=\"https://docs.expo.dev/guides/typescript/\" rel=\"nofollow\">Expo</a>: <code>npx create-expo-app -t with-typescript</code></li>\n</ul>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-try-react-and-typescript-online\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#try-react-and-typescript-online\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Try React and TypeScript online</h4>\n<p dir=\"auto\">There are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.</p>\n<ul dir=\"auto\">\n<li><a href=\"https://www.typescriptlang.org/play?target=8&amp;jsx=4#code/JYWwDg9gTgLgBAbzgVwM4FMDKMCGN0A0KGAogGZnoDG8AvnGVBCHAORTo42sDcAsAChB6AB6RYcKhAB2qeAGEIyafihwAvHAAUASg0A+RILiSZcuAG0pymEQwxFNgLobiWXPi0AGHfyECTNHRyShotXQMjAJM4ABMIKmQQdBUAOhhgGAAbdFcAAwBNJUks4CoAa3RYuAASBGsVegzk1Dy-E1pfQWM4DhhkKGltHpMAHn0RmNGwfSLkErLK6vqlRrhm9FRRgHoZybGAI2QYGBk4GXlSivUECPVDe0cVLQb4AGo4AEYdWgnomJil0WcGS+zgOyOJxkfwBOxhcC6AlogiAA\" rel=\"nofollow\">TypeScript playground</a></li>\n<li><a href=\"https://stackblitz.com/fork/react-ts\" rel=\"nofollow\">StackBlitz</a></li>\n<li><a href=\"https://ts.react.new/\" rel=\"nofollow\">CodeSandbox</a></li>\n</ul>\n\n<h3 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-section-2-getting-started\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#section-2-getting-started\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Section 2: Getting Started</h3>\n\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-function-components\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#function-components\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Function Components</h4>\n<p dir=\"auto\">These can be written as normal functions that take a <code>props</code> argument and return a JSX element.</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"// Declaring type of props - see &quot;Typing Component Props&quot; for more examples\ntype AppProps = {\n message: string;\n}; /* use `interface` if exporting so that consumers can extend */\n\n// Easiest way to declare a Function Component; return type is inferred.\nconst App = ({ message }: AppProps) =&gt; &lt;div&gt;{message}&lt;/div&gt;;\n\n// you can choose annotate the return type so an error is raised if you accidentally return some other type\nconst App = ({ message }: AppProps): React.JSX.Element =&gt; &lt;div&gt;{message}&lt;/div&gt;;\n\n// you can also inline the type declaration; eliminates naming the prop types, but looks repetitive\nconst App = ({ message }: { message: string }) =&gt; &lt;div&gt;{message}&lt;/div&gt;;\n\n// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.\n// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.\nconst App: React.FunctionComponent&lt;{ message: string }&gt; = ({ message }) =&gt; (\n &lt;div&gt;{message}&lt;/div&gt;\n);\"><pre><span class=\"pl-c\">// Declaring type of props - see \"Typing Component Props\" for more examples</span>\n<span class=\"pl-k\">type</span> <span class=\"pl-smi\">AppProps</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">/* use `interface` if exporting so that consumers can extend */</span>\n\n<span class=\"pl-c\">// Easiest way to declare a Function Component; return type is inferred.</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">App</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> message <span class=\"pl-kos\">}</span>: <span class=\"pl-smi\">AppProps</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">message</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// you can choose annotate the return type so an error is raised if you accidentally return some other type</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">App</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> message <span class=\"pl-kos\">}</span>: <span class=\"pl-smi\">AppProps</span><span class=\"pl-kos\">)</span>: <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">JSX</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">Element</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">message</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// you can also inline the type declaration; eliminates naming the prop types, but looks repetitive</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">App</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> message <span class=\"pl-kos\">}</span>: <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">message</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.</span>\n<span class=\"pl-c\">// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">App</span>: <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">FunctionComponent</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-kos\">{</span> <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> message <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">message</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n<span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<blockquote>\n<p dir=\"auto\">Tip: You might use <a href=\"https://marketplace.visualstudio.com/items?itemName=paulshen.paul-typescript-toolkit\" rel=\"nofollow\">Paul Shen's VS Code Extension</a> to automate the type destructure declaration (incl a <a href=\"https://twitter.com/_paulshen/status/1392915279466745857?s=20\" rel=\"nofollow\">keyboard shortcut</a>).</p>\n</blockquote>\n<details>\n<summary><b>Why is <code>React.FC</code> not needed? What about <code>React.FunctionComponent</code>/<code>React.VoidFunctionComponent</code>?</b></summary>\n<p dir=\"auto\">You may see this in many React+TypeScript codebases:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"const App: React.FunctionComponent&lt;{ message: string }&gt; = ({ message }) =&gt; (\n &lt;div&gt;{message}&lt;/div&gt;\n);\"><pre><span class=\"pl-k\">const</span> <span class=\"pl-smi\">App</span>: <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">FunctionComponent</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-kos\">{</span> <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> message <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">message</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n<span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">However, the general consensus today is that <code>React.FunctionComponent</code> (or the shorthand <code>React.FC</code>) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is even <a href=\"https://github.com/facebook/create-react-app/pull/8177\" data-hovercard-type=\"pull_request\" data-hovercard-url=\"/facebook/create-react-app/pull/8177/hovercard\">discouraged</a>. This is a nuanced opinion of course, but if you agree and want to remove <code>React.FC</code> from your codebase, you can use <a href=\"https://github.com/gndelia/codemod-replace-react-fc-typescript\">this jscodeshift codemod</a>.</p>\n<p dir=\"auto\">Some differences from the \"normal function\" version:</p>\n<ul dir=\"auto\">\n<li>\n<p dir=\"auto\"><code>React.FunctionComponent</code> is explicit about the return type, while the normal function version is implicit (or else needs additional annotation).</p>\n</li>\n<li>\n<p dir=\"auto\">It provides typechecking and autocomplete for static properties like <code>displayName</code>, <code>propTypes</code>, and <code>defaultProps</code>.</p>\n<ul dir=\"auto\">\n<li>Note that there are some known issues using <code>defaultProps</code> with <code>React.FunctionComponent</code>. See <a href=\"https://github.com/typescript-cheatsheets/react/issues/87\" data-hovercard-type=\"issue\" data-hovercard-url=\"/typescript-cheatsheets/react/issues/87/hovercard\">this issue for details</a>. We maintain a separate <code>defaultProps</code> section you can also look up.</li>\n</ul>\n</li>\n<li>\n<p dir=\"auto\">Before the <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210\" data-hovercard-type=\"pull_request\" data-hovercard-url=\"/DefinitelyTyped/DefinitelyTyped/pull/56210/hovercard\">React 18 type updates</a>, <code>React.FunctionComponent</code> provided an implicit definition of <code>children</code> (see below), which was heavily debated and is one of the reasons <a href=\"https://github.com/facebook/create-react-app/pull/8177\" data-hovercard-type=\"pull_request\" data-hovercard-url=\"/facebook/create-react-app/pull/8177/hovercard\"><code>React.FC</code> was removed from the Create React App TypeScript template</a>.</p>\n</li>\n</ul>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"// before React 18 types\nconst Title: React.FunctionComponent&lt;{ title: string }&gt; = ({\n children,\n title,\n}) =&gt; &lt;div title={title}&gt;{children}&lt;/div&gt;;\"><pre><span class=\"pl-c\">// before React 18 types</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">Title</span>: <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">FunctionComponent</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-kos\">{</span> <span class=\"pl-c1\">title</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span>\n children<span class=\"pl-kos\">,</span>\n title<span class=\"pl-kos\">,</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span> <span class=\"pl-c1\">title</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">title</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">children</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span></pre></div>\n<details>\n<summary>(Deprecated)<b>Using <code>React.VoidFunctionComponent</code> or <code>React.VFC</code> instead</b></summary>\n<p dir=\"auto\">In <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/pull/46643\" data-hovercard-type=\"pull_request\" data-hovercard-url=\"/DefinitelyTyped/DefinitelyTyped/pull/46643/hovercard\">@types/react 16.9.48</a>, the <code>React.VoidFunctionComponent</code> or <code>React.VFC</code> type was added for typing <code>children</code> explicitly.\nHowever, please be aware that <code>React.VFC</code> and <code>React.VoidFunctionComponent</code> were deprecated in React 18 (<a class=\"issue-link js-issue-link\" data-error-text=\"Failed to load title\" data-id=\"1203510582\" data-permission-text=\"Title is private\" data-url=\"https://github.com/DefinitelyTyped/DefinitelyTyped/issues/59882\" data-hovercard-type=\"pull_request\" data-hovercard-url=\"/DefinitelyTyped/DefinitelyTyped/pull/59882/hovercard\" href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/pull/59882\">DefinitelyTyped/DefinitelyTyped#59882</a>), so this interim solution is no longer necessary or recommended in React 18+.</p>\n<p dir=\"auto\">Please use regular function components or <code>React.FC</code> instead.</p>\n<div class=\"highlight highlight-source-ts notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"type Props = { foo: string };\n\n// OK now, in future, error\nconst FunctionComponent: React.FunctionComponent&lt;Props&gt; = ({\n foo,\n children,\n}: Props) =&gt; {\n return (\n &lt;div&gt;\n {foo} {children}\n &lt;/div&gt;\n ); // OK\n};\n\n// Error now, in future, deprecated\nconst VoidFunctionComponent: React.VoidFunctionComponent&lt;Props&gt; = ({\n foo,\n children,\n}) =&gt; {\n return (\n &lt;div&gt;\n {foo}\n {children}\n &lt;/div&gt;\n );\n};\"><pre><span class=\"pl-k\">type</span> <span class=\"pl-smi\">Props</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">foo</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// OK now, in future, error</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">FunctionComponent</span>: <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">FunctionComponent</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">Props</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span>\n foo<span class=\"pl-kos\">,</span>\n children<span class=\"pl-kos\">,</span>\n<span class=\"pl-kos\">}</span>: <span class=\"pl-smi\">Props</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">div</span><span class=\"pl-kos\">&gt;</span>\n <span class=\"pl-kos\">{</span>foo<span class=\"pl-kos\">}</span> <span class=\"pl-kos\">{</span>children<span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-pds\"><span class=\"pl-c1\">/</span>div&gt;</span><span class=\"pl-c1\"></span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">// OK</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// Error now, in future, deprecated</span>\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">VoidFunctionComponent</span>: <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-smi\">VoidFunctionComponent</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">Props</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span>\n foo<span class=\"pl-kos\">,</span>\n children<span class=\"pl-kos\">,</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">div</span><span class=\"pl-kos\">&gt;</span>\n <span class=\"pl-kos\">{</span>foo<span class=\"pl-kos\">}</span>\n <span class=\"pl-kos\">{</span>children<span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-pds\"><span class=\"pl-c1\">/</span>div&gt;</span><span class=\"pl-c1\"></span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span></pre></div>\n</details>\n<ul dir=\"auto\">\n<li><em>In the future</em>, it may automatically mark props as <code>readonly</code>, though that's a moot point if the props object is destructured in the parameter list.</li>\n</ul>\n<p dir=\"auto\">In most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of <code>React.FunctionComponent</code>.</p>\n</details>\n\n\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-hooks\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#hooks\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Hooks</h4>\n<p dir=\"auto\">Hooks are <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L800-L1031\">supported in <code>@types/react</code> from v16.8 up</a>.</p>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-usestate\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#usestate\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>useState</h4>\n<p dir=\"auto\">Type inference works very well for simple values:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"const [state, setState] = useState(false);\n// `state` is inferred to be a boolean\n// `setState` only takes booleans\"><pre><span class=\"pl-k\">const</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">state</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">setState</span><span class=\"pl-kos\">]</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">false</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-c\">// `state` is inferred to be a boolean</span>\n<span class=\"pl-c\">// `setState` only takes booleans</span></pre></div>\n<p dir=\"auto\">See also the <a href=\"https://react-typescript-cheatsheet.netlify.app/docs/basic/troubleshooting/types/#using-inferred-types\" rel=\"nofollow\">Using Inferred Types</a> section if you need to use a complex type that you've relied on inference for.</p>\n<p dir=\"auto\">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:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"const [user, setUser] = useState&lt;User | null&gt;(null);\n\n// later...\nsetUser(newUser);\"><pre><span class=\"pl-k\">const</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">user</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">setUser</span><span class=\"pl-kos\">]</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useState</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">User</span> <span class=\"pl-c1\">|</span> <span class=\"pl-c1\">null</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">null</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// later...</span>\n<span class=\"pl-en\">setUser</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">newUser</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">You can also use type assertions if a state is initialized soon after setup and always has a value after:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"const [user, setUser] = useState&lt;User&gt;({} as User);\n\n// later...\nsetUser(newUser);\"><pre><span class=\"pl-k\">const</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">user</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">setUser</span><span class=\"pl-kos\">]</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useState</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">User</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span> <span class=\"pl-k\">as</span> <span class=\"pl-smi\">User</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-c\">// later...</span>\n<span class=\"pl-en\">setUser</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">newUser</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">This temporarily \"lies\" to the TypeScript compiler that <code>{}</code> is of type <code>User</code>. You should follow up by setting the <code>user</code> state — if you don't, the rest of your code may rely on the fact that <code>user</code> is of type <code>User</code> and that may lead to runtime errors.</p>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-usecallback\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#usecallback\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>useCallback</h4>\n<p dir=\"auto\">You can type the <code>useCallback</code> just like any other function.</p>\n<div class=\"highlight highlight-source-ts notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"const memoizedCallback = useCallback(\n (param1: string, param2: number) =&gt; {\n console.log(param1, param2)\n return { ok: true }\n },\n [...],\n);\n/**\n * VSCode will show the following type:\n * const memoizedCallback:\n * (param1: string, param2: number) =&gt; { ok: boolean }\n */\"><pre><span class=\"pl-k\">const</span> <span class=\"pl-s1\">memoizedCallback</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useCallback</span><span class=\"pl-kos\">(</span>\n <span class=\"pl-kos\">(</span><span class=\"pl-s1\">param1</span>: <span class=\"pl-smi\">string</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">param2</span>: <span class=\"pl-smi\">number</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-smi\">console</span><span class=\"pl-kos\">.</span><span class=\"pl-en\">log</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">param1</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">param2</span><span class=\"pl-kos\">)</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">ok</span>: <span class=\"pl-c1\">true</span> <span class=\"pl-kos\">}</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-kos\">[</span>...<span class=\"pl-kos\">]</span><span class=\"pl-kos\">,</span>\n<span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-c\">/**</span>\n<span class=\"pl-c\"> * VSCode will show the following type:</span>\n<span class=\"pl-c\"> * const memoizedCallback:</span>\n<span class=\"pl-c\"> * (param1: string, param2: number) =&gt; { ok: boolean }</span>\n<span class=\"pl-c\"> */</span></pre></div>\n<p dir=\"auto\">Note that for React &lt; 18, the function signature of <code>useCallback</code> typed arguments as <code>any[]</code> by default:</p>\n<div class=\"highlight highlight-source-ts notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function useCallback&lt;T extends (...args: any[]) =&gt; any&gt;(\n callback: T,\n deps: DependencyList\n): T;\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-s1\">useCallback</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-smi\">T</span> <span class=\"pl-k\">extends</span> <span class=\"pl-kos\">(</span>...<span class=\"pl-s1\">args</span>: <span class=\"pl-smi\">any</span><span class=\"pl-kos\">[</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-smi\">any</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">(</span>\n <span class=\"pl-s1\">callback</span>: <span class=\"pl-smi\">T</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-s1\">deps</span>: <span class=\"pl-smi\">DependencyList</span>\n<span class=\"pl-kos\">)</span>: <span class=\"pl-smi\">T</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">In React &gt;= 18, the function signature of <code>useCallback</code> changed to the following:</p>\n<div class=\"highlight highlight-source-ts notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function useCallback&lt;T extends Function&gt;(callback: T, deps: DependencyList): T;\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-s1\">useCallback</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-smi\">T</span> <span class=\"pl-k\">extends</span> <span class=\"pl-smi\">Function</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">callback</span>: <span class=\"pl-smi\">T</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">deps</span>: <span class=\"pl-smi\">DependencyList</span><span class=\"pl-kos\">)</span>: <span class=\"pl-smi\">T</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">Therefore, the following code will yield \"<code>Parameter 'e' implicitly has an 'any' type.</code>\" error in React &gt;= 18, but not &lt;17.</p>\n<div class=\"highlight highlight-source-ts notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"// @ts-expect-error Parameter 'e' implicitly has 'any' type.\nuseCallback((e) =&gt; {}, []);\n// Explicit 'any' type.\nuseCallback((e: any) =&gt; {}, []);\"><pre><span class=\"pl-c\">// <span class=\"pl-k\">@ts</span>-expect-error Parameter 'e' implicitly has 'any' type.</span>\n<span class=\"pl-en\">useCallback</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">e</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">[</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-c\">// Explicit 'any' type.</span>\n<span class=\"pl-en\">useCallback</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">e</span>: <span class=\"pl-smi\">any</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">[</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-usereducer\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#usereducer\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>useReducer</h4>\n<p dir=\"auto\">You can use <a href=\"https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions\" rel=\"nofollow\">Discriminated Unions</a> for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"import { useReducer } from &quot;react&quot;;\n\nconst initialState = { count: 0 };\n\ntype ACTIONTYPE =\n | { type: &quot;increment&quot;; payload: number }\n | { type: &quot;decrement&quot;; payload: string };\n\nfunction reducer(state: typeof initialState, action: ACTIONTYPE) {\n switch (action.type) {\n case &quot;increment&quot;:\n return { count: state.count + action.payload };\n case &quot;decrement&quot;:\n return { count: state.count - Number(action.payload) };\n default:\n throw new Error();\n }\n}\n\nfunction Counter() {\n const [state, dispatch] = useReducer(reducer, initialState);\n return (\n &lt;&gt;\n Count: {state.count}\n &lt;button onClick={() =&gt; dispatch({ type: &quot;decrement&quot;, payload: &quot;5&quot; })}&gt;\n -\n &lt;/button&gt;\n &lt;button onClick={() =&gt; dispatch({ type: &quot;increment&quot;, payload: 5 })}&gt;\n +\n &lt;/button&gt;\n &lt;/&gt;\n );\n}\"><pre><span class=\"pl-k\">import</span> <span class=\"pl-kos\">{</span> <span class=\"pl-s1\">useReducer</span> <span class=\"pl-kos\">}</span> <span class=\"pl-k\">from</span> <span class=\"pl-s\">\"react\"</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">const</span> <span class=\"pl-s1\">initialState</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">count</span>: <span class=\"pl-c1\">0</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">type</span> <span class=\"pl-smi\">ACTIONTYPE</span> <span class=\"pl-c1\">=</span>\n <span class=\"pl-c1\">|</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">type</span>: <span class=\"pl-s\">\"increment\"</span><span class=\"pl-kos\">;</span> <span class=\"pl-c1\">payload</span>: <span class=\"pl-smi\">number</span> <span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">|</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">type</span>: <span class=\"pl-s\">\"decrement\"</span><span class=\"pl-kos\">;</span> <span class=\"pl-c1\">payload</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">function</span> <span class=\"pl-en\">reducer</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">state</span>: <span class=\"pl-k\">typeof</span> <span class=\"pl-s1\">initialState</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">action</span>: <span class=\"pl-smi\">ACTIONTYPE</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">switch</span> <span class=\"pl-kos\">(</span><span class=\"pl-s1\">action</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">type</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">case</span> <span class=\"pl-s\">\"increment\"</span>:\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">count</span>: <span class=\"pl-s1\">state</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">count</span> <span class=\"pl-c1\">+</span> <span class=\"pl-s1\">action</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">payload</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">case</span> <span class=\"pl-s\">\"decrement\"</span>:\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">count</span>: <span class=\"pl-s1\">state</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">count</span> <span class=\"pl-c1\">-</span> <span class=\"pl-smi\">Number</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">action</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">payload</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">default</span>:\n <span class=\"pl-k\">throw</span> <span class=\"pl-k\">new</span> <span class=\"pl-smi\">Error</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span>\n<span class=\"pl-kos\">}</span>\n\n<span class=\"pl-k\">function</span> <span class=\"pl-smi\">Counter</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">state</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">dispatch</span><span class=\"pl-kos\">]</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useReducer</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">reducer</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">initialState</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">&gt;</span>\n Count: <span class=\"pl-kos\">{</span><span class=\"pl-s1\">state</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">count</span><span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">button</span> <span class=\"pl-c1\">onClick</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-en\">dispatch</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> <span class=\"pl-c1\">type</span>: <span class=\"pl-s\">\"decrement\"</span><span class=\"pl-kos\">,</span> <span class=\"pl-c1\">payload</span>: <span class=\"pl-s\">\"5\"</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&gt;</span>\n -\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">button</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">button</span> <span class=\"pl-c1\">onClick</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-en\">dispatch</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span> <span class=\"pl-c1\">type</span>: <span class=\"pl-s\">\"increment\"</span><span class=\"pl-kos\">,</span> <span class=\"pl-c1\">payload</span>: <span class=\"pl-c1\">5</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&gt;</span>\n +\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">button</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\"><a href=\"https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6WfTDRSvKnMgpEIgBhxTIJwEQANZSWRjI5SdPIF1u8RXMayZ7lSphEnRWLxbFNagAVmomhF6fZqYA9OXKxxM2KQWWK1WoTW643m63pB2u+7e-3SkEQsPamOGik1FO55p08jl6vdxuKcvv8h4yAmhAA\" rel=\"nofollow\">View in the TypeScript Playground</a></p>\n<details>\n<summary><b>Usage with <code>Reducer</code> from <code>redux</code></b></summary>\n<p dir=\"auto\">In case you use the <a href=\"https://github.com/reduxjs/redux\">redux</a> library to write reducer function, It provides a convenient helper of the format <code>Reducer&lt;State, Action&gt;</code> which takes care of the return type for you.</p>\n<p dir=\"auto\">So the above reducer example becomes:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"import { Reducer } from 'redux';\n\nexport function reducer: Reducer&lt;AppState, Action&gt;() {}\"><pre><span class=\"pl-k\">import</span> <span class=\"pl-kos\">{</span> <span class=\"pl-smi\">Reducer</span> <span class=\"pl-kos\">}</span> <span class=\"pl-k\">from</span> <span class=\"pl-s\">'redux'</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">export</span> <span class=\"pl-k\">function</span> <span class=\"pl-s1\">reducer</span>: <span class=\"pl-smi\">Reducer</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-smi\">AppState</span><span class=\"pl-kos\">,</span> <span class=\"pl-smi\">Action</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span></pre></div>\n</details>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-useeffect--uselayouteffect\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#useeffect--uselayouteffect\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>useEffect / useLayoutEffect</h4>\n<p dir=\"auto\">Both of <code>useEffect</code> and <code>useLayoutEffect</code> are used for performing <b>side effects</b> and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using <code>useEffect</code>, take care not to return anything other than a function or <code>undefined</code>, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:</p>\n<div class=\"highlight highlight-source-ts notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function DelayedEffect(props: { timerMs: number }) {\n const { timerMs } = props;\n\n useEffect(\n () =&gt;\n setTimeout(() =&gt; {\n /* do stuff */\n }, timerMs),\n [timerMs]\n );\n // bad example! setTimeout implicitly returns a number\n // because the arrow function body isn't wrapped in curly braces\n return null;\n}\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-smi\">DelayedEffect</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">props</span>: <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">timerMs</span>: <span class=\"pl-smi\">number</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-kos\">{</span> timerMs <span class=\"pl-kos\">}</span> <span class=\"pl-c1\">=</span> <span class=\"pl-s1\">props</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-en\">useEffect</span><span class=\"pl-kos\">(</span>\n <span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span>\n <span class=\"pl-en\">setTimeout</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">/* do stuff */</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">timerMs</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-kos\">[</span><span class=\"pl-s1\">timerMs</span><span class=\"pl-kos\">]</span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-c\">// bad example! setTimeout implicitly returns a number</span>\n <span class=\"pl-c\">// because the arrow function body isn't wrapped in curly braces</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-c1\">null</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<details>\n<summary><b>Solution to the above example</b></summary>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function DelayedEffect(props: { timerMs: number }) {\n const { timerMs } = props;\n\n useEffect(() =&gt; {\n setTimeout(() =&gt; {\n /* do stuff */\n }, timerMs);\n }, [timerMs]);\n // better; use the void keyword to make sure you return undefined\n return null;\n}\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-smi\">DelayedEffect</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">props</span>: <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">timerMs</span>: <span class=\"pl-smi\">number</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-kos\">{</span> timerMs <span class=\"pl-kos\">}</span> <span class=\"pl-c1\">=</span> <span class=\"pl-s1\">props</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-en\">useEffect</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-en\">setTimeout</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">/* do stuff */</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">timerMs</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">timerMs</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-c\">// better; use the void keyword to make sure you return undefined</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-c1\">null</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n</details>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-useref\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#useref\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>useRef</h4>\n<p dir=\"auto\">In TypeScript, <code>useRef</code> returns a reference that is either <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1025-L1039\">read-only</a> or <a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/blob/abd69803c1b710db58d511f4544ec1b70bc9077c/types/react/v16/index.d.ts#L1012-L1023\">mutable</a>, depends on whether your type argument fully covers the initial value or not. Choose one that suits your use case.</p>\n<h5 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-option-1-dom-element-ref\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#option-1-dom-element-ref\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Option 1: DOM element ref</h5>\n<p dir=\"auto\"><strong><a href=\"https://reactjs.org/docs/refs-and-the-dom.html\" rel=\"nofollow\">To access a DOM element</a>:</strong> provide only the element type as argument, and use <code>null</code> as initial value. In this case, the returned reference will have a read-only <code>.current</code> that is managed by React. TypeScript expects you to give this ref to an element's <code>ref</code> prop:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function Foo() {\n // - If possible, prefer as specific as possible. For example, HTMLDivElement\n // is better than HTMLElement and way better than Element.\n // - Technical-wise, this returns RefObject&lt;HTMLDivElement&gt;\n const divRef = useRef&lt;HTMLDivElement&gt;(null);\n\n useEffect(() =&gt; {\n // Note that ref.current may be null. This is expected, because you may\n // conditionally render the ref-ed element, or you may forget to assign it\n if (!divRef.current) throw Error(&quot;divRef is not assigned&quot;);\n\n // Now divRef.current is sure to be HTMLDivElement\n doSomethingWith(divRef.current);\n });\n\n // Give the ref to an element so React can manage it for you\n return &lt;div ref={divRef}&gt;etc&lt;/div&gt;;\n}\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-smi\">Foo</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// - If possible, prefer as specific as possible. For example, HTMLDivElement</span>\n <span class=\"pl-c\">// is better than HTMLElement and way better than Element.</span>\n <span class=\"pl-c\">// - Technical-wise, this returns RefObject&lt;HTMLDivElement&gt;</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">divRef</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">HTMLDivElement</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">null</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-en\">useEffect</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// Note that ref.current may be null. This is expected, because you may</span>\n <span class=\"pl-c\">// conditionally render the ref-ed element, or you may forget to assign it</span>\n <span class=\"pl-k\">if</span> <span class=\"pl-kos\">(</span><span class=\"pl-c1\">!</span><span class=\"pl-s1\">divRef</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">)</span> <span class=\"pl-k\">throw</span> <span class=\"pl-smi\">Error</span><span class=\"pl-kos\">(</span><span class=\"pl-s\">\"divRef is not assigned\"</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-c\">// Now divRef.current is sure to be HTMLDivElement</span>\n <span class=\"pl-en\">doSomethingWith</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">divRef</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-c\">// Give the ref to an element so React can manage it for you</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span> <span class=\"pl-c1\">ref</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">divRef</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&gt;</span>etc<span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\">If you are sure that <code>divRef.current</code> will never be null, it is also possible to use the non-null assertion operator <code>!</code>:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"const divRef = useRef&lt;HTMLDivElement&gt;(null!);\n// Later... No need to check if it is null\ndoSomethingWith(divRef.current);\"><pre><span class=\"pl-k\">const</span> <span class=\"pl-s1\">divRef</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">HTMLDivElement</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">null</span><span class=\"pl-c1\">!</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-c\">// Later... No need to check if it is null</span>\n<span class=\"pl-en\">doSomethingWith</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">divRef</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">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.</p>\n<details>\n<summary><b>Tip: Choosing which <code>HTMLElement</code> to use</b></summary>\n<p dir=\"auto\">Refs demand specificity - it is not enough to just specify any old <code>HTMLElement</code>. If you don't know the name of the element type you need, you can check <a href=\"https://github.com/microsoft/TypeScript/blob/v3.9.5/lib/lib.dom.d.ts#L19224-L19343\">lib.dom.ts</a> or make an intentional type error and let the language service tell you:</p>\n<p dir=\"auto\"><a target=\"_blank\" rel=\"noopener noreferrer nofollow\" href=\"https://user-images.githubusercontent.com/6764957/116914284-1c436380-ac7d-11eb-9150-f52c571c5f07.png\"><img src=\"https://user-images.githubusercontent.com/6764957/116914284-1c436380-ac7d-11eb-9150-f52c571c5f07.png\" alt=\"image\" style=\"max-width: 100%;\"></a></p>\n</details>\n<h5 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-option-2-mutable-value-ref\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#option-2-mutable-value-ref\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Option 2: Mutable value ref</h5>\n<p dir=\"auto\"><strong><a href=\"https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables\" rel=\"nofollow\">To have a mutable value</a>:</strong> provide the type you want, and make sure the initial value fully belongs to that type:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function Foo() {\n // Technical-wise, this returns MutableRefObject&lt;number | null&gt;\n const intervalRef = useRef&lt;number | null&gt;(null);\n\n // You manage the ref yourself (that's why it's called MutableRefObject!)\n useEffect(() =&gt; {\n intervalRef.current = setInterval(...);\n return () =&gt; clearInterval(intervalRef.current);\n }, []);\n\n // The ref is not passed to any element's &quot;ref&quot; prop\n return &lt;button onClick={/* clearInterval the ref */}&gt;Cancel timer&lt;/button&gt;;\n}\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-smi\">Foo</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// Technical-wise, this returns MutableRefObject&lt;number | null&gt;</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">intervalRef</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">number</span> <span class=\"pl-c1\">|</span> <span class=\"pl-c1\">null</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">null</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-c\">// You manage the ref yourself (that's why it's called MutableRefObject!)</span>\n <span class=\"pl-en\">useEffect</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-s1\">intervalRef</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">setInterval</span><span class=\"pl-kos\">(</span>...<span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-en\">clearInterval</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">intervalRef</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">[</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-c\">// The ref is not passed to any element's \"ref\" prop</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">button</span> <span class=\"pl-c1\">onClick</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-c\">/* clearInterval the ref */</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&gt;</span>Cancel timer<span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">button</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<h5 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-see-also\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#see-also\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>See also</h5>\n<ul dir=\"auto\">\n<li><a href=\"https://github.com/typescript-cheatsheets/react/issues/388\" data-hovercard-type=\"issue\" data-hovercard-url=\"/typescript-cheatsheets/react/issues/388/hovercard\">Related issue by @rajivpunjabi</a> - <a href=\"https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcARFDvmQNwCwAUI7hAHarwCCYYcAvHAAUASn4A+OAG9GjOHAD0CBLLnKGcxHABiwKBzgQwMYGxS4WUACbBWAczgwIcSxFwBXEFlYxkxtgDoVTQBJVmBjZAAbOAA3KLcsOAB3YEjogCNE1jc0-zgAGQBPG3tHOAAVQrAsAGVcKGAjOHTCuDdUErhWNgBabLSUVFQsWBNWA2qoX2hA9VU4AGFKXyx0AFk3H3TIxOwCOAB5dIArLHwgpHcoSm84MGJJmFbgdG74ZcsDVkjC2Y01f7yFQsdjvLAEACM-EwVBg-naWD2AB4ABLlNb5GpgZCsACiO083jEgn6kQAhMJ6HMQfpKJCFpE2IkBNg8HCEci0RisTj8VhCTBiaSKVSVIoAaoLnBQuFgFFYvFEikBpkujkMps4FgAB7VfCdLmY7F4gleOFwAByEHg7U63VYfXVg2Go1MhhG0ygf3mAHVUtF6jgYLtwUdTvguta4Bstjs9mGznCpVcbvB7u7YM90B8vj9vYgLkDqWxaeCAEzQ1n4eHDTnoo2801EknqykyObii5SmpnNifA5GMZmCzWOwOJwudwC3xjKUyiLROKRBLJf3NLJO9KanV64xj0koVifQ08k38s1Sv0DJZBxIx5DbRGhk6J5Nua5mu4PEZPOAvSNgsgnxsHmXZzIgRZyDSYIEAAzJWsI1k+BCovWp58gKcAAD5qmkQqtqKHbyCexoYRecw7IQugcAs76ptCdIQv4KZmoRcjyMRaGkU28A4aSKiUXAwwgpYtEfrcAh0mWzF0ax7bsZx3Lceetx8eqAlYPAMAABa6KJskSXAdKwTJ4kwGxCjyKy-bfK05SrDA8mWVagHAbZeScOY0CjqUE6uOgqDaRAOSfKqOYgb8KiMaZ9GSeCEIMkyMVyUwRHWYc7nSvAgUQEk6AjMQXpReWyWGdFLHeBZHEuTCQEZT8xVwaV8BxZCzUWZQMDvuMghBHASJVnCWhTLYApiH1chIqgxpGeCfCSIxAC+Yj3o+8YvvgSLyNNOLjeBGhTTNdLzVJy3reGMBbTtrB7RoB3XbNBAneCsHLatcbPhdV3GrdB1WYhw3IKNZq-W2DCLYRO7QPAljgsgORcDwVJAA\" rel=\"nofollow\">Playground</a></li>\n<li><a href=\"https://fettblog.eu/typescript-react/hooks/#useref\" rel=\"nofollow\">Example from Stefan Baumgartner</a> - <a href=\"https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wFgAoCzAVwDsNgJa4AVJADxgElaxqYA6sBgALAGIQ01AM4AhfjCYAKAJRwA3hThwA9DrjBaw4CgA2waUjgB3YSLi1qp0wBo4AI35wYSZ6wCeYEgAymhQwGDw1lYoRHCmEBAA1oYA5nCY0HAozAASLACyADI8fDAAoqZIIEi0MFpwaEzS8IZllXAAvIjEMAB0MkjImAA8+cWl-JXVtTAAfEqOzioA3A1NtC1wTPIwirQAwuZoSV1wql1zGg3aenAt4RgOTqaNIkgn0g5ISAAmcDJvBA3h9TsBMAZeFNXjl-lIoEQ6nAOBZ+jddPpPPAmGgrPDEfAUS1pG5hAYvhAITBAlZxiUoRUqjU6m5RIDhOi7iIUF9RFYaqIIP9MlJpABCOCAUHJ0eDzm1oXAAGSKyHtUx9fGzNSacjaPWq6Ea6gI2Z9EUyVRrXV6gC+DRtVu0RBgxuYSnRIzm6O06h0ACpIdlfr9jExSQyOkxTP5GjkPFZBv9bKIDYSmbNpH04ABNFD+CV+nR2636kby+BETCddTlyo27w0zr4HycfC6L0lvUjLH7baHY5Jas7BRMI7AE42uYSUXed6pkY6HtMDulnQruCrCg2oA\" rel=\"nofollow\">Playground</a></li>\n</ul>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-useimperativehandle\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#useimperativehandle\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>useImperativeHandle</h4>\n<p dir=\"auto\">Based on this <a href=\"https://stackoverflow.com/a/69292925/5415299\" rel=\"nofollow\">Stackoverflow answer</a>:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"// Countdown.tsx\n\n// Define the handle types which will be passed to the forwardRef\nexport type CountdownHandle = {\n start: () =&gt; void;\n};\n\ntype CountdownProps = {};\n\nconst Countdown = forwardRef&lt;CountdownHandle, CountdownProps&gt;((props, ref) =&gt; {\n useImperativeHandle(ref, () =&gt; ({\n // start() has type inference here\n start() {\n alert(&quot;Start&quot;);\n },\n }));\n\n return &lt;div&gt;Countdown&lt;/div&gt;;\n});\"><pre><span class=\"pl-c\">// Countdown.tsx</span>\n\n<span class=\"pl-c\">// Define the handle types which will be passed to the forwardRef</span>\n<span class=\"pl-k\">export</span> <span class=\"pl-k\">type</span> <span class=\"pl-smi\">CountdownHandle</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">start</span>: <span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-smi\"><span class=\"pl-k\">void</span></span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">type</span> <span class=\"pl-smi\">CountdownProps</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">const</span> <span class=\"pl-smi\">Countdown</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">forwardRef</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">CountdownHandle</span><span class=\"pl-kos\">,</span> <span class=\"pl-smi\">CountdownProps</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">props</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">ref</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-en\">useImperativeHandle</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">ref</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// start() has type inference here</span>\n <span class=\"pl-en\">start</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-en\">alert</span><span class=\"pl-kos\">(</span><span class=\"pl-s\">\"Start\"</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-k\">return</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>Countdown<span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span></pre></div>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"// The component uses the Countdown component\n\nimport Countdown, { CountdownHandle } from &quot;./Countdown.tsx&quot;;\n\nfunction App() {\n const countdownEl = useRef&lt;CountdownHandle&gt;(null);\n\n useEffect(() =&gt; {\n if (countdownEl.current) {\n // start() has type inference here as well\n countdownEl.current.start();\n }\n }, []);\n\n return &lt;Countdown ref={countdownEl} /&gt;;\n}\"><pre><span class=\"pl-c\">// The component uses the Countdown component</span>\n\n<span class=\"pl-k\">import</span> <span class=\"pl-smi\">Countdown</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">{</span> <span class=\"pl-smi\">CountdownHandle</span> <span class=\"pl-kos\">}</span> <span class=\"pl-k\">from</span> <span class=\"pl-s\">\"./Countdown.tsx\"</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">function</span> <span class=\"pl-smi\">App</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">countdownEl</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">CountdownHandle</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">null</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-en\">useEffect</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">if</span> <span class=\"pl-kos\">(</span><span class=\"pl-s1\">countdownEl</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// start() has type inference here as well</span>\n <span class=\"pl-s1\">countdownEl</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">.</span><span class=\"pl-en\">start</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">[</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n\n <span class=\"pl-k\">return</span> <span class=\"pl-c1\">&lt;</span><span class=\"pl-smi\">Countdown</span> <span class=\"pl-c1\">ref</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-s1\">countdownEl</span><span class=\"pl-kos\">}</span> <span class=\"pl-c1\">/</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<h5 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-see-also-1\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#see-also-1\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>See also:</h5>\n<ul dir=\"auto\">\n<li><a href=\"https://stackoverflow.com/a/62258685/5415299\" rel=\"nofollow\">Using ForwardRefRenderFunction</a></li>\n</ul>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-custom-hooks\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#custom-hooks\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Custom Hooks</h4>\n<p dir=\"auto\">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 <a href=\"https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions\" rel=\"nofollow\">TS 3.4 const assertions</a>:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"import { useState } from &quot;react&quot;;\n\nexport function useLoading() {\n const [isLoading, setState] = useState(false);\n const load = (aPromise: Promise&lt;any&gt;) =&gt; {\n setState(true);\n return aPromise.finally(() =&gt; setState(false));\n };\n return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]\n}\"><pre><span class=\"pl-k\">import</span> <span class=\"pl-kos\">{</span> <span class=\"pl-s1\">useState</span> <span class=\"pl-kos\">}</span> <span class=\"pl-k\">from</span> <span class=\"pl-s\">\"react\"</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">export</span> <span class=\"pl-k\">function</span> <span class=\"pl-en\">useLoading</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">isLoading</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">setState</span><span class=\"pl-kos\">]</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">false</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-en\">load</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-s1\">aPromise</span>: <span class=\"pl-smi\">Promise</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">any</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-en\">setState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">true</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-s1\">aPromise</span><span class=\"pl-kos\">.</span><span class=\"pl-en\">finally</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-en\">setState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">false</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">isLoading</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">load</span><span class=\"pl-kos\">]</span> <span class=\"pl-k\">as</span> <span class=\"pl-smi\">const</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">// infers [boolean, typeof load] instead of (boolean | typeof load)[]</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\"><a href=\"https://www.typescriptlang.org/play/?target=5&amp;jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCpAD0ljkwFcA7DYCZuRgZyQBkIKACbBmAcwAUASjgBvCnDhoO3eAG1g3AcNFiANHF4wAyjBQwkAXTgBeRMRgA6HklPmkEzCgA2vKQG4FJRV4b0EhWzgJFAAFHBBNJAAuODjcRIAeFGYATwA+GRs8uSDFIzcLCRgoRiQA0rgiGEYoTlj4xMdMUR9vHIlpW2Lys0qvXzr68kUAX0DpxqRm1rgNLXDdAzDhaxRuYOZVfzgAehO4UUwkKH21ACMICG9UZgMYHLAkCEw4baFrUSqVARb5RB5PF5wAA+cHen1BfykaksFBmQA\" rel=\"nofollow\">View in the TypeScript Playground</a></p>\n<p dir=\"auto\">This way, when you destructure you actually get the right types based on destructure position.</p>\n<details>\n<summary><b>Alternative: Asserting a tuple return type</b></summary>\n<p dir=\"auto\">If you are <a href=\"https://github.com/babel/babel/issues/9800\" data-hovercard-type=\"issue\" data-hovercard-url=\"/babel/babel/issues/9800/hovercard\">having trouble with const assertions</a>, you can also assert or define the function return types:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"import { useState } from &quot;react&quot;;\n\nexport function useLoading() {\n const [isLoading, setState] = useState(false);\n const load = (aPromise: Promise&lt;any&gt;) =&gt; {\n setState(true);\n return aPromise.finally(() =&gt; setState(false));\n };\n return [isLoading, load] as [\n boolean,\n (aPromise: Promise&lt;any&gt;) =&gt; Promise&lt;any&gt;\n ];\n}\"><pre><span class=\"pl-k\">import</span> <span class=\"pl-kos\">{</span> <span class=\"pl-s1\">useState</span> <span class=\"pl-kos\">}</span> <span class=\"pl-k\">from</span> <span class=\"pl-s\">\"react\"</span><span class=\"pl-kos\">;</span>\n\n<span class=\"pl-k\">export</span> <span class=\"pl-k\">function</span> <span class=\"pl-en\">useLoading</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">isLoading</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">setState</span><span class=\"pl-kos\">]</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">false</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-en\">load</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-s1\">aPromise</span>: <span class=\"pl-smi\">Promise</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">any</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-en\">setState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">true</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-s1\">aPromise</span><span class=\"pl-kos\">.</span><span class=\"pl-en\">finally</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-en\">setState</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">false</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">isLoading</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">load</span><span class=\"pl-kos\">]</span> <span class=\"pl-k\">as</span> <span class=\"pl-kos\">[</span>\n <span class=\"pl-smi\">boolean</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-kos\">(</span><span class=\"pl-s1\">aPromise</span>: <span class=\"pl-smi\">Promise</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">any</span><span class=\"pl-kos\">&gt;</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-smi\">Promise</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">any</span><span class=\"pl-kos\">&gt;</span>\n <span class=\"pl-kos\">]</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\">A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"function tuplify&lt;T extends any[]&gt;(...elements: T) {\n return elements;\n}\n\nfunction useArray() {\n const numberValue = useRef(3).current;\n const functionValue = useRef(() =&gt; {}).current;\n return [numberValue, functionValue]; // type is (number | (() =&gt; void))[]\n}\n\nfunction useTuple() {\n const numberValue = useRef(3).current;\n const functionValue = useRef(() =&gt; {}).current;\n return tuplify(numberValue, functionValue); // type is [number, () =&gt; void]\n}\"><pre><span class=\"pl-k\">function</span> <span class=\"pl-en\">tuplify</span><span class=\"pl-c1\">&lt;</span><span class=\"pl-smi\">T</span> <span class=\"pl-k\">extends</span> <span class=\"pl-smi\">any</span><span class=\"pl-kos\">[</span><span class=\"pl-kos\">]</span><span class=\"pl-c1\">&gt;</span><span class=\"pl-kos\">(</span>...<span class=\"pl-s1\">elements</span>: <span class=\"pl-smi\">T</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-s1\">elements</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span>\n\n<span class=\"pl-k\">function</span> <span class=\"pl-en\">useArray</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">numberValue</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">3</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">functionValue</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">[</span><span class=\"pl-s1\">numberValue</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">functionValue</span><span class=\"pl-kos\">]</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">// type is (number | (() =&gt; void))[]</span>\n<span class=\"pl-kos\">}</span>\n\n<span class=\"pl-k\">function</span> <span class=\"pl-en\">useTuple</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">numberValue</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">3</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">const</span> <span class=\"pl-s1\">functionValue</span> <span class=\"pl-c1\">=</span> <span class=\"pl-en\">useRef</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span><span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">current</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-en\">tuplify</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">numberValue</span><span class=\"pl-kos\">,</span> <span class=\"pl-s1\">functionValue</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">// type is [number, () =&gt; void]</span>\n<span class=\"pl-kos\">}</span></pre></div>\n</details>\n<p dir=\"auto\">Note that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however.</p>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-more-hooks--typescript-reading\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#more-hooks--typescript-reading\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>More Hooks + TypeScript reading:</h4>\n<ul dir=\"auto\">\n<li><a href=\"https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d\" rel=\"nofollow\">https://medium.com/@jrwebdev/react-hooks-in-typescript-88fce7001d0d</a></li>\n<li><a href=\"https://fettblog.eu/typescript-react/hooks/#useref\" rel=\"nofollow\">https://fettblog.eu/typescript-react/hooks/#useref</a></li>\n</ul>\n<p dir=\"auto\">If you are writing a React Hooks library, don't forget that you should also expose your types for users to use.</p>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-example-react-hooks--typescript-libraries\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#example-react-hooks--typescript-libraries\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Example React Hooks + TypeScript Libraries:</h4>\n<ul dir=\"auto\">\n<li><a href=\"https://github.com/mweststrate/use-st8\">https://github.com/mweststrate/use-st8</a></li>\n<li><a href=\"https://github.com/palmerhq/the-platform\">https://github.com/palmerhq/the-platform</a></li>\n<li><a href=\"https://github.com/sw-yx/hooks\">https://github.com/sw-yx/hooks</a></li>\n</ul>\n<p dir=\"auto\"><a href=\"https://github.com/typescript-cheatsheets/react/issues/new\">Something to add? File an issue</a>.</p>\n\n\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-class-components\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#class-components\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"><path d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"></path></svg></a>Class Components</h4>\n<p dir=\"auto\">Within TypeScript, <code>React.Component</code> is a generic type (aka <code>React.Component&lt;PropType, StateType&gt;</code>), so you want to provide it with (optional) prop and state type parameters:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"type MyProps = {\n // using `interface` is also ok\n message: string;\n};\ntype MyState = {\n count: number; // like this\n};\nclass App extends React.Component&lt;MyProps, MyState&gt; {\n state: MyState = {\n // optional second annotation for better type inference\n count: 0,\n };\n render() {\n return (\n &lt;div&gt;\n {this.props.message} {this.state.count}\n &lt;/div&gt;\n );\n }\n}\"><pre><span class=\"pl-k\">type</span> <span class=\"pl-smi\">MyProps</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// using `interface` is also ok</span>\n <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-k\">type</span> <span class=\"pl-smi\">MyState</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">count</span>: <span class=\"pl-smi\">number</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">// like this</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-k\">class</span> <span class=\"pl-smi\">App</span> <span class=\"pl-k\">extends</span> <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">Component</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-smi\">MyProps</span><span class=\"pl-kos\">,</span> <span class=\"pl-smi\">MyState</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">state</span>: <span class=\"pl-smi\">MyState</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// optional second annotation for better type inference</span>\n <span class=\"pl-c1\">count</span>: <span class=\"pl-c1\">0</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-en\">render</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">{</span><span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">props</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">message</span><span class=\"pl-kos\">}</span> <span class=\"pl-kos\">{</span><span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">state</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">count</span><span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\"><a href=\"https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCmATzCTgFlqAFHMAZzgF44BvCuHAD0QuAFd2wAHYBzOAANpMJFEzok8uME4oANuwhwIAawFwQSduxQykALjjsYUaTIDcFAL4fyNOo2oAZRgUZW4+MzQIMSkYBykxEAAjFTdhUV1gY3oYAAttLx80XRQrOABBMDA4JAAPZSkAE05kdBgAOgBhXEgpJFiAHiZWCA4AGgDg0KQAPgjyQSdphyYpsJ5+BcF0ozAYYAgpPUckKKa4FCkpCBD9w7hMaDgUmGUoOD96aUwVfrQkMyCKIxOJwAAMZm8ZiITRUAAoAJTzbZwIgwMRQKRwOGA7YDRrAABuM1xKN4eW07TAbHY7QsVhsSE8fAptKWynawNinlJcAGQgJxNxCJ8gh55E8QA\" rel=\"nofollow\">View in the TypeScript Playground</a></p>\n<p dir=\"auto\">Don't forget that you can export/import/extend these types/interfaces for reuse.</p>\n<details>\n<summary><b>Why annotate <code>state</code> twice?</b></summary>\n<p dir=\"auto\">It isn't strictly necessary to annotate the <code>state</code> class property, but it allows better type inference when accessing <code>this.state</code> and also initializing the state.</p>\n<p dir=\"auto\">This is because they work in two different ways, the 2nd generic type parameter will allow <code>this.setState()</code> to work correctly, because that method comes from the base class, but initializing <code>state</code> 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.</p>\n<p dir=\"auto\"><a href=\"https://github.com/typescript-cheatsheets/react/issues/57\" data-hovercard-type=\"issue\" data-hovercard-url=\"/typescript-cheatsheets/react/issues/57/hovercard\">See commentary by @ferdaber here</a>.</p>\n</details>\n<details>\n <summary><b>No need for <code>readonly</code></b></summary>\n<p dir=\"auto\">You often see sample code include <code>readonly</code> to mark props and state immutable:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"type MyProps = {\n readonly message: string;\n};\ntype MyState = {\n readonly count: number;\n};\"><pre><span class=\"pl-k\">type</span> <span class=\"pl-smi\">MyProps</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">readonly</span> <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-k\">type</span> <span class=\"pl-smi\">MyState</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">readonly</span> <span class=\"pl-c1\">count</span>: <span class=\"pl-smi\">number</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span></pre></div>\n<p dir=\"auto\">This is not necessary as <code>React.Component&lt;P,S&gt;</code> already marks them as immutable. (<a href=\"https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813\" data-hovercard-type=\"pull_request\" data-hovercard-url=\"/DefinitelyTyped/DefinitelyTyped/pull/26813/hovercard\">See PR and discussion!</a>)</p>\n</details>\n<p dir=\"auto\"><strong>Class Methods</strong>: Do it like normal, but just remember any arguments for your functions also need to be typed:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"class App extends React.Component&lt;{ message: string }, { count: number }&gt; {\n state = { count: 0 };\n render() {\n return (\n &lt;div onClick={() =&gt; this.increment(1)}&gt;\n {this.props.message} {this.state.count}\n &lt;/div&gt;\n );\n }\n increment = (amt: number) =&gt; {\n // like this\n this.setState((state) =&gt; ({\n count: state.count + amt,\n }));\n };\n}\"><pre><span class=\"pl-k\">class</span> <span class=\"pl-smi\">App</span> <span class=\"pl-k\">extends</span> <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">Component</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-kos\">{</span> <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">,</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">count</span>: <span class=\"pl-smi\">number</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">state</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">{</span> <span class=\"pl-c1\">count</span>: <span class=\"pl-c1\">0</span> <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-en\">render</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span> <span class=\"pl-c1\">onClick</span><span class=\"pl-c1\">=</span><span class=\"pl-kos\">{</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-en\">increment</span><span class=\"pl-kos\">(</span><span class=\"pl-c1\">1</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">}</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">{</span><span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">props</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">message</span><span class=\"pl-kos\">}</span> <span class=\"pl-kos\">{</span><span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">state</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">count</span><span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">increment</span> <span class=\"pl-c1\">=</span> <span class=\"pl-kos\">(</span><span class=\"pl-s1\">amt</span>: <span class=\"pl-smi\">number</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c\">// like this</span>\n <span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-en\">setState</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">(</span><span class=\"pl-s1\">state</span><span class=\"pl-kos\">)</span> <span class=\"pl-c1\">=&gt;</span> <span class=\"pl-kos\">(</span><span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">count</span>: <span class=\"pl-s1\">state</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">count</span> <span class=\"pl-c1\">+</span> <span class=\"pl-s1\">amt</span><span class=\"pl-kos\">,</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\"><a href=\"https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN5wQSBigDmSAFxw6MKMB5q4AXwA0cRWggBXHjG09rIAEZIoJgHwWKcHTBTccAC8FnBWtvZwAAwmANw+cET8bgAUAJTe5L6+RDDWUDxwKQnZcLJ8wABucBA8YtTAaADWQfLpwV4wABbAdCIGaETKdikAjGnGHiWlFt29ImA4YH3KqhrGsz19ugFIIuF2xtO+sgD0FZVTWdlp8ddH1wNDMsFFKCCRji5uGUFe8tNTqc4A0mkg4HM6NNISI6EgYABlfzcFI7QJ-IoA66lA6RNF7XFwADUcHeMGmxjStwSxjuxiAA\" rel=\"nofollow\">View in the TypeScript Playground</a></p>\n<p dir=\"auto\"><strong>Class Properties</strong>: If you need to declare class properties for later use, just declare it like <code>state</code>, but without assignment:</p>\n<div class=\"highlight highlight-source-tsx notranslate position-relative overflow-auto\" dir=\"auto\" data-snippet-clipboard-copy-content=\"class App extends React.Component&lt;{\n message: string;\n}&gt; {\n pointer: number; // like this\n componentDidMount() {\n this.pointer = 3;\n }\n render() {\n return (\n &lt;div&gt;\n {this.props.message} and {this.pointer}\n &lt;/div&gt;\n );\n }\n}\"><pre><span class=\"pl-k\">class</span> <span class=\"pl-smi\">App</span> <span class=\"pl-k\">extends</span> <span class=\"pl-smi\">React</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">Component</span><span class=\"pl-kos\">&lt;</span><span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">message</span>: <span class=\"pl-smi\">string</span><span class=\"pl-kos\">;</span>\n<span class=\"pl-kos\">}</span><span class=\"pl-kos\">&gt;</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-c1\">pointer</span>: <span class=\"pl-smi\">number</span><span class=\"pl-kos\">;</span> <span class=\"pl-c\">// like this</span>\n <span class=\"pl-en\">componentDidMount</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">pointer</span> <span class=\"pl-c1\">=</span> <span class=\"pl-c1\">3</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span>\n <span class=\"pl-en\">render</span><span class=\"pl-kos\">(</span><span class=\"pl-kos\">)</span> <span class=\"pl-kos\">{</span>\n <span class=\"pl-k\">return</span> <span class=\"pl-kos\">(</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">{</span><span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">props</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">message</span><span class=\"pl-kos\">}</span> and <span class=\"pl-kos\">{</span><span class=\"pl-smi\">this</span><span class=\"pl-kos\">.</span><span class=\"pl-c1\">pointer</span><span class=\"pl-kos\">}</span>\n <span class=\"pl-c1\">&lt;</span><span class=\"pl-c1\">/</span><span class=\"pl-ent\">div</span><span class=\"pl-c1\">&gt;</span>\n <span class=\"pl-kos\">)</span><span class=\"pl-kos\">;</span>\n <span class=\"pl-kos\">}</span>\n<span class=\"pl-kos\">}</span></pre></div>\n<p dir=\"auto\"><a href=\"https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wFgAoCtAGxQGc64BBMMOJADxiQDsATRsnQwAdAGFckHrxgAeAN4U4cEEgYoA5kgBccOjCjAeGgNwUAvgD44i8sshHuUXTwCuIAEZIoJuAHo-OGpgAGskOBgAC2A6JTg0SQhpHhgAEWA+AFkIVxSACgBKGzjlKJiRBxTvOABeOABmMzs4cziifm9C4ublIhhXKB44PJLlOFk+YAA3S1GxmzK6CpwwJdV1LXM4FH4F6KXKp1aesdk-SZnRgqblY-MgA\" rel=\"nofollow\">View in the TypeScript Playground</a></p>\n<p dir=\"auto\"><a href=\"https://github.com/typescript-cheatsheets/react/issues/new\">Something to add? File an issue</a>.</p>\n<h4 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-typing-getderivedstatefromprops\" class=\"anchor\" aria-hidden=\"true\" tabindex=\"-1\" href=\"#typing-getderivedstatefromprops\"><svg class=\"octicon octicon-link\" viewBox=\"0 0 16 16