Typing of React hooks in Typescript

Marcel Mokos
ableneo Technology
Published in
3 min readMay 21, 2020

--

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.

Inferring type

Typescript can infer 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 useHook<type>(arg) 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…

--

--

Marcel Mokos
ableneo Technology

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