Back

React TypeScript Cheatsheet

React TypeScript Cheatsheet

1. Getting Started

React TypeScript Cheatsheets are for experienced React developers getting started with TypeScript.

2. Hooks

2.1 useState

Type inference works well for simple values:

const [state, setState] = useState(false);

For complex types, explicitly declare the type:

const [user, setUser] = useState<User | null>(null);

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

2.3 useReducer

You can use Discriminated Unions for reducer actions:

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

2.4 useEffect / useLayoutEffect

Both of useEffect and useLayoutEffect are used for performing side effects and return an optional cleanup function2.

3. Advanced Cheatsheet

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

4. Setup

React and TypeScript starter kits are available. React has documentation for how to start a new React project with some of the most popular frameworks4. These starter kits can help you set up a new project quickly, with a structure that follows best practices.

React and TypeScript starter kits are available. They provide a pre-configured environment with a structure that follows best practices. You can start a new React project with some of the most popular frameworks. For more detailed information, refer to the original React TypeScript Cheatsheets.

5. Basic Types

5.1 Primitive Types

In TypeScript, there are several basic primitive types:

let isDone: boolean = false;
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let color: string = "blue";

5.2 Array

TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways:

let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];

5.3 Tuple

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same:

let x: [string, number];
x = ["hello", 10]; // OK

6. Interfaces

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types:

interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);

7. Classes

TypeScript offers full class-based object-oriented programming:

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("world");

8. Generics

Generics are a way to create reusable components which can work over a variety of types rather than a single one. This allows users to consume these components and use their own types.

function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>("myString");
---
title: Generics
---

Generics in TypeScript allow for the creation of reusable components that can work over a variety of types, not just a single one. This means you can consume these components and use your own types. Here's a basic example:

```typescript
function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>("myString");
```