Typing of React hooks in Typescript

Marcel Mokos
May 21 · 3 min read

Explain to me the setState. Hooks are now the better option to do effects in react. Using hooks with typescript can be complicated at first let’s dive in.

Image for post
Image for post

Inferring type

Typescript can gues types based on the parameters.

const [value, setValue] = useState("");   // const value: string
const [value, setValue] = useState(0); // const value: number
const [value, setValue] = useState(true); // const value: boolean
// const setValue: Dispatch<SetStateAction<State>>

Providing type

Type can be provided by syntax called Typescript Generics.

const [value, setValue] = useState<string>("");
// const value: string
const [value, setValue] = useState<number>(0);
// const value: number
const [value, setValue] = useState<boolean>(true);
// const value: boolean

Typescript Generics

Many of you can know generics from other languages such as C# or Java. The motivation for generics is to allow universal functions that can infer the type of the output based on input.

Let’s use a simplified useState hook type as an example.

function useState<State>(initialState: State): [State, ...];

Function type declaration is using as generic for a future type of the array output ignore the second item in the array now.

In simple language, the useState expect type provided in or it will use the type from initialState argument.

Image for post
Image for post

Overloading types

Typescript allows state multiple function type declaration.

function useState<S>(initialState: S): [S, ...];
function useState<S>(initialState: (() => S)): [S, ...];
const [value, setValue] = useState(() => "");
// const value: string

Example of useState hook with initialState provided by the initialization function. The real type of declaration is using called syntax.

function useState<S>(initialState: S | (() => S)): [S, ...];

Type aliases

The useState hook is returning an array with two items the other item can set the value or in other words change the state.

const [value, setValue] = useState<string>("");
// const value: string
// const setValue: Dispatch<SetStateAction<string>>

Full type declaration of useState hook. Is using aliases is just wrapping any function and saying it will return or other words it won't return anything.

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];type Dispatch<A> = (value: A) => void;
type SetStateAction<S> = S | ((prevState: S) => S);

type is similar to the overloaded type of . The user of the function can set the state directly or use the function with the previous state as an argument.

const [value, setValue] = useState(0);setValue(1);
setValue((prevState) => prevState + 1);

If you want to know why previous example will have value equal to 1. You can read article explaining why

Image for post
Image for post

Explore types of other hooks and create your own reusable hooks

Going more in-depth of all the React hooks is better to do on your own. With knowledge from you can read types and documentation and you will be able to use and type hooks.

Example of the hook

A use case for the that can save a reference to any previous value. Useful for optimizations and comparing with previous values.

import {useEffect, useRef} from "react";

export const usePrevious = <Value = any>(value: Value): Value => {
const ref = useRef<Value>();

useEffect(() => {
ref.current = value;
}, [value]);

return ref.current;
};

ableneo Technology

Application Development, Data Science, Experience Platforms

Marcel Mokos

Written by

I'm fanatic to next generation Javascript lambda, yield, async/await everything. I admire typescript and flow types. Javascript will ultimately rule the world.

ableneo Technology

Application Development, Data Science, Experience Platforms

Marcel Mokos

Written by

I'm fanatic to next generation Javascript lambda, yield, async/await everything. I admire typescript and flow types. Javascript will ultimately rule the world.

ableneo Technology

Application Development, Data Science, Experience Platforms

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store