Released in React v16.8.0, React Hooks address a number of issues with React, and perhaps most notably for TypeScript users, provide a first-class solution for reusing stateful logic, built with typing in mind. Due to this, a lot of the types for Hooks can be inferred, but in some cases explicit types must be set.

This article assumes some knowledge of the Hooks that are available. For this refer to the React documentation.

useState

useContext

useEffect / useLayoutEffect

useMemo / useCallback

Note: you must make sure you specify the types of the parameters of the callback for useCallback, otherwise they will be set to any, regardless of whether you have TypeScript’s noImplicitAny set to true.

useRef

Since the introduction of Hooks, useRef can also be used as a replacement for instance properties on classes, in which case the type can be inferred and current becomes mutable:

useReducer

useImperativeHandle

The above example wraps an HTML input component and exposes a focus function in order to allow the input to be focussed. Firstly, an interface MyInputHandles is declared to specify the functions that will be exposed through the ref. This interface is then passed to RefForwardingComponent to set it up as a component that can have a ref passed to it, which is implemented using forwardRef. From this, useImperativeHandle can infer the types, so you will receive a compilation error if you do not implement the interface as the return value of the factory function in second argument.

The ref can then be used by using MyInputHandles in the generic passed to useRef:

useDebugValue

Web developer currently working with TypeScript, React and Node in Auckland, New Zealand.

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