...

/

React and TypeScript: `useState` Hook

React and TypeScript: `useState` Hook

This lesson is a detailed analysis of typing the `useState` hook in TypeScript.

Overview

React hooks are a recent addition to React that make function components have almost the same capabilities as class components. Most of the time, using React hooks in TypeScript is straightforward.

However, there are some situations when a deeper understanding of a hook’s type might prove useful. In this lesson, we’re going to focus on the useState hook.

I’m going to assume that you have a basic understanding of this hook. If this is not the case, please read this first.

Reading the types

First of all, let’s take a look at the type signature of useState. You’ll see how much information you can extract solely from types, without looking at the docs or the implementation.

Overloads

function useState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

As you can see, there are two versions of the useState function. TypeScript lets you define multiple type signatures for a function as it is often the case in JavaScript that a function supports different types of parameters. Multiple type signatures for a single function are called overloads.

Both overloads are generic functions. The type parameter S represents the type of the piece of state stored by the hook. The type argument in the second overload can ...