typescript-cheatsheets/react(新しいタブで開きます)
主要言語: TypeScript
Cheatsheets for experienced React developers getting started with TypeScript
- star 数
- 47,080
- watcher 数
- 389
- fork 数
- 4,265
- issue 数
- 0
- 最終更新
- 2026/09/10
主要言語: TypeScript
Cheatsheets for experienced React developers getting started with TypeScript
Cheatsheet for using React with TypeScript.
Web docs | Contribute! | Ask!
👋 This repo is maintained by @eps1lon and @filiptammergard. We're so happy you want to try out React with TypeScript! If you see anything wrong or missing, please file an issue! 👍
The Cheatsheet is focused on helping React devs use TypeScript effectively:
defaultPropsdefaultPropsYou 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 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:
npx create-next-app@latest --tsnpx create-remix@latestnpm init gatsby --tsnpx create-expo-app -t with-typescriptIf you just want a client-side single-page app without a framework, Vite is the most common choice:
npm create vite@latest my-app -- --template react-tsThere are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.
These can be written as normal functions that take a props argument and return a JSX element.
// Declaring type of props - see "Typing Component Props" for more examples type AppProps = { message: string; }; /* use `interface` if exporting so that consumers can extend */ // Easiest way to declare a Function Component; return type is inferred. const App = ({ message }: AppProps) => <div>{message}</div>; // You can choose to annotate the return type so an error is raised if you accidentally return some other type const App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>; // You can also inline the type declaration; eliminates naming the prop types, but looks repetitive const App = ({ message }: { message: string }) => <div>{message}</div>; // Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer. // With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged. const App: React.FunctionComponent<{ message: string }> = ({ message }) => ( <div>{message}</div> ); // or const App: React.FC<AppProps> = ({ message }) => <div>{message}</div>;
Why isTip: You might use Paul Shen's VS Code Extension to automate the type destructure declaration (incl a keyboard shortcut).
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.
defaultProps with React.FunctionComponent. See this issue for details. We maintain a separate defaultProps section you can also look up.In the future, it may automatically mark props as readonly, though that's a moot point if the props object is destructured in the parameter list.
In most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature of React.FunctionComponent.
Hooks are supported in @types/react from v16.8 up.
Type inference works very well for simple values:
const [state, setState] = useState(false); // `state` is inferred to be a boolean // `setState` only takes booleans
If you need to use a complex type that you've relied on inference for, you can use typeof to capture the inferred type.
However, many hooks are initialized with null-ish default values, and you may wonder how to provide types. Explicitly declare the type, and use a union type:
const [user, setUser] = useState<User | null>(null); // later... setUser(newUser);
You can also use type assertions if a state is initialized soon after setup and always has a value after:
const [user, setUser] = useState<User>({} as User); // later... setUser(newUser);
This temporarily "lies" to the TypeScript compiler that {} is of type User. You should follow up by setting the user state — if you don't, the rest of your code may rely on the fact that user is of type User and that may lead to runtime errors.
You can type the useCallback just like any other function.
const memoizedCallback = useCallback( (param1: string, param2: number) => { console.log(param1, param2) return { ok: true } }, [...], ); /** * VSCode will show the following type: * const memoizedCallback: * (param1: string, param2: number) => { ok: boolean } */
Note that for React < 18, the function signature of useCallback typed arguments as any[] by default:
function useCallback<T extends (...args: any[]) => any>( callback: T, deps: DependencyList, ): T;
In React >= 18, the function signature of useCallback changed to the following:
function useCallback<T extends Function>(callback: T, deps: DependencyList): T;
Therefore, the following code will yield "Parameter 'e' implicitly has an 'any' type." error in React >= 18, but not <17.
// @ts-expect-error Parameter 'e' implicitly has 'any' type. useCallback((e) => {}, []); // Explicit 'any' type. useCallback((e: any) => {}, []);
You can use Discriminated Unions for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.
import { useReducer } from "react"; const initialState = { count: 0 }; type ACTIONTYPE = | { type: "increment"; payload: number } | { type: "decrement"; payload: string }; function reducer( state: typeof initialState, action: ACTIONTYPE, ): typeof initialState { 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 withReducer 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>() {}
useReducer
In most cases, type inference for useReducer should work reliably. When inference fails, the state and action types can be explicitly provided using the following syntax, where the action type is wrapped in a single-element tuple.
const [state, dispatch] = useReducer<typeof initialState, [ACTIONTYPE]>( reducer, initialState, );
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; }
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 always returns a RefObject<T> in current @types/react. An initial value is required, and the returned .current is typed based on it. (MutableRefObject is deprecated and only kept for backwards compatibility.)
To access a DOM element: provide the element type as a generic and pass null as the initial value. React manages .current for you, and TypeScript expects you to pass 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 whichHTMLElement to use
Refs demand specificity - it is not enough to just specify any old HTMLElement. If you don't know the name of the element type you need, you can check lib.dom.ts or make an intentional type error and let the language service tell you:
To hold a mutable value across renders without re-rendering on change: pass the initial value you want — React doesn't manage .current for you here, you write to it manually.
function Foo() { const intervalRef = useRef<number | null>(null); useEffect(() => { intervalRef.current = window.setInterval(() => { /* ... */ }, 1000); return () => { if (intervalRef.current !== null) clearInterval(intervalRef.current); }; }, []); return ( <button onClick={() => { /* clearInterval the ref */ }} > Cancel timer </button> ); }
In React 19, ref is a regular prop on function components, so useImperativeHandle is called with the ref prop directly — no forwardRef needed.
// Countdown.tsx import { useImperativeHandle, Ref } from "react"; export type CountdownHandle = { start: () => void; }; type CountdownProps = { ref?: Ref<CountdownHandle>; }; const Countdown = ({ ref }: CountdownProps) => { useImperativeHandle(ref, () => ({ // start() has type inference here start() { alert("Start"); }, })); return <div>Countdown</div>; };
// The component using the Countdown component import { useEffect, useRef } from "react"; import Countdown, { CountdownHandle } from "./Countdown.tsx"; function App() { const countdownEl = useRef<CountdownHandle>(null); useEffect(() => { if (countdownEl.current) { // start() has type inference here as well countdownEl.current.start(); } }, []); return <Countdown ref={countdownEl} />; }
If you still maintain code that targets React < 19, see the forwardRef section for the legacy approach using
forwardRef<CountdownHandle, CountdownProps>.
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 typeIf 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.
If you are writing a React Hooks library, don't forget that you should also expose your types for users to use.
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 annotatestate 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 forreadonly
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, define them directly within the class body without an initial 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
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
getDerivedStateFromProps conforms to it.class Comp extends React.Component<Props, State> { static getDerivedStateFromProps( props: Props, state: State, ): Partial<State> | null { // } }
class Comp extends React.Component< Props, ReturnType<(typeof Comp)["getDerivedStateFromProps"]> > { static getDerivedStateFromProps(props: Props) {} }
type CustomValue = any; interface Props { propA: CustomValue; } interface DefinedState { otherStateField: string; } type State = DefinedState & ReturnType<typeof transformPropsToState>; function transformPropsToState(props: Props) { return { savedPropA: props.propA, // save for memoization derivedState: props.propA, }; } class Comp extends React.PureComponent<Props, State> { constructor(props: Props) { super(props); this.state = { otherStateField: "123", ...transformPropsToState(props), }; } static getDerivedStateFromProps(props: Props, state: State) { if (isEqual(props.propA, state.savedPropA)) return null; return transformPropsToState(props); } }
View in the TypeScript Playground
As of React 19, defaultProps is no longer supported on function components. Use destructuring defaults directly in the parameter list — TypeScript will infer the prop as optional automatically:
type GreetProps = { age?: number }; const Greet = ({ age = 21 }: GreetProps) => { // ... };
If you prefer to declare defaults separately (for example, to share them across components), pull them into a constant and spread them when destructuring:
type GreetProps = { age?: number }; const defaultProps = { age: 21 } satisfies GreetProps; const Greet = ({ age = defaultProps.age }: GreetProps) => { // ... };
Setting
Greet.defaultProps = { age: 21 }will not work on function components in React 19 — the value is ignored at runtime andFunctionComponentno longer types it.
Class components still support static defaultProps. The recommended approach is to type the props with the defaulted keys as required, and let LibraryManagedAttributes (applied automatically by JSX) make them optional at the call site:
type GreetProps = { age: number; }; class Greet extends React.Component<GreetProps> { static defaultProps = { age: 21, }; render() { return <div>Hello, I am {this.props.age}</div>; } } // Type-checks — `age` is optional at the call site thanks to defaultProps. const el = <Greet />;
React.JSX.LibraryManagedAttributes nuance for library authors
If you export GreetProps for consumers, age will appear required even though defaultProps makes it optional at the call site. GreetProps is the internal contract — there's a separate external contract that JSX computes via React.JSX.LibraryManagedAttributes. You can compute it explicitly:
// internal contract — don't export type GreetProps = { age: number; }; class Greet extends React.Component<GreetProps> { static defaultProps = { age: 21 }; } // external contract export type ApparentGreetProps = React.JSX.LibraryManagedAttributes< typeof Greet, GreetProps >;
For most apps this isn't needed — only library authors who re-export the props type tend to hit it.
This is intended as a basic orientation and reference for React developers familiarizing with TypeScript.
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 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, bigint, 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.
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;
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/basic/getting-started/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 }
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.createElementReact.ReactNode -> Return value of a componentMore discussion: Where ReactNode does not overlap with React.JSX.Element
You can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?
Use Interface until You Need Type - orta.
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.
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)
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
| |
| |
| |
| |