Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

react

> 前端框架
Open source

Cheatsheets for experienced React developers getting started with TypeScript

250.8K stars0 likes1 views
WebsiteGitHub

About

Cheatsheets for experienced React developers getting started with TypeScript

React TypeScript Cheatsheet

Cheatsheet for using React with TypeScript.


Web docs | Contribute! | Ask!

:wave: 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! :+1:


|

The Cheatsheet is focused on helping React devs use TypeScript effectively:

  • Opinionated best practices and copy+pastable examples.
  • Covers basic TS types and setup, plus advanced usage of generic types for people writing reusable type utilities and React+TS libraries.
  • Advice for contributing to DefinitelyTyped.

Cheatsheet

Table of Contents

Expand Table of Contents
  • React TypeScript Cheatsheet
    • Cheatsheet
      • Table of Contents
      • Setup
        • Prerequisites
        • React and TypeScript starter kits
        • Try React and TypeScript online
      • Getting Started
        • Function Components
        • Hooks
        • useState
        • useCallback
        • useReducer
        • useEffect / useLayoutEffect
        • useRef
          • Option 1: DOM element ref
          • Option 2: Mutable value ref
          • See also
        • useImperativeHandle
          • See also:
        • Custom Hooks
        • More Hooks + TypeScript reading:
        • Example React Hooks + TypeScript Libraries:
        • Class Components
        • Typing getDerivedStateFromProps
        • You May Not Need defaultProps
        • Typing defaultProps
        • Consuming Props of a Component with defaultProps
          • Problem Statement
          • Solution
        • Misc Discussions and Knowledge
        • Typing Component Props
        • Basic Prop Types Examples
          • object as the non-primitive type
          • Empty interface, {} and Object
        • Useful React Prop Type Examples
        • Types or Interfaces?
          • TL;DR
          • More Advice
          • Useful table for Types vs Interfaces
    • getDerivedStateFromProps
      • Forms and Events
        • List of event types
      • Context
      • Basic example
      • Without default context value
        • Type assertion as an alternative
      • forwardRef/createRef
      • Generic forwardRefs
        • Option 1 - Wrapper component
        • Option 2 - Redeclare forwardRef
        • Option 3 - Call signature
      • More Info
      • Portals
      • Error Boundaries
        • Option 1: Using react-error-boundary
        • Option 2: Writing your custom error boundary component
      • Concurrent React/React Suspense
    • My question isn't answered here!
    • Contributors

Introduction

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:

  • Basic understanding of React.
  • Familiarity with TypeScript Basics and Everyday Types.

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

React 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

If you just want a client-side single-page app without a framework, Vite is the most common choice:

  • Vite: npm create vite@latest my-app -- --template react-ts

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.

  • TypeScript playground
  • StackBlitz
  • CodeSandbox

Getting Started

Function Components

These can be written as normal functions that take a props argument and return a JSX element.

…

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:

typescript
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
  

);

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

typescript
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:

typescript
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:

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

typescript
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:

typescript
function useCallback<T extends (...args: any[]) => any>(
  callback: T,
  deps: DependencyList,
): T;

In React >= 18, the function signature of useCallback changed to the following:

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

typescript
// @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.

…

[View in the TypeScript Playground](https://www.typescriptlang.org/play?#code/LAKFEsFsAcHsCcAuACAVMghgZ2QJQKYYDGKAZvLJMgOTyEnUDcooRsAdliuO+IuBgA2AZUQZE+ZAF5kAbzYBXdogBcyAAwBfZmBCIAntEkBBAMIAVAJIB5AHLmAmgAUAotOShkyAD5zkBozVqHiI6SHxlagAaZGgMfUFYDAATNXYFSAAjfHhNDxAvX1l-Q3wg5PxQ-HDImLiEpNTkLngeAHM8ll1SJRJwDmQ6ZIUiHIAKLnEykqNYUmQePgERMQkY4n4ONTMrO0dXAEo5T2aAdz4iAAtkMY3+9gA6APwj2ROvImxJYPYqmsRqCp3l5BvhEAp4Ow5IplGpJhIHjCUABqTB9DgPeqJFLaYGfLDfCp-CIAoEFEFeOjgyHQ2BKVTNVb4RF05TIAC0yFsGWy8Fu6MeWMaB1x5K8FVIGAUglUwK8iEuFFOyHY+GVLngFD5Bx0Xk0oH13V6myhplZEm1x3JbE4KAA2vD8DFkuAsHFEFcALruAgbB4KAkEYajPlDEY5GKLfhCURTHUnKkQqFjYEAHgAfHLkGb6WpZI6

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptcheatsheetguidereacttypescript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 9, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架