React Hooks in TypeScript

James Ravenscroft
Feb 13, 2019 · 3 min read
Image for post
Image for post

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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