Using React Hooks with TypeScript

The next version of React (16.7.0-alpha.0) was recently released with added support for React Hooks. Hooks bring many of the features that were only available with class components to function components and can help solve other problems, like “wrapper hell.”

Photo by rawpixel on Unsplash.

There is already great documentation coverage for Hooks, and I would recommend reading the React Hooks documentation if you have not yet. The remainder of this article will cover the necessary steps to create a basic React TypeScript app to experiment with the new Hooks API, in a type-safe way!

Edit 2018/11/10: The steps below were updated since create-react-app v2.1 was released with TypeScript support and @types/react v16.7.0 was released with hook type support.

The easiest way to create a React app is to use the appropriately named create-react-appproject. It allows creating React apps in one command without the hassle (like webpack or TypeScript configs).

It’ no longer necessary to use the react-scripts-ts script to create a TypeScript React app. The most recent release of create-react-app (v2.1) supports TypeScript out of the box!

create-react-app react-hooks-typescript-example --typescript

This command will set up and install all of the necessary configs and packages. By default, it will install the latest stable version of React. However, Hooks are only available in the next version of React (16.7.0-alpha.0), so it’s necessary to upgrade the react and react-dom packages.

yarn upgrade react@next react-dom@next

The typings have now been updated to support React Hooks so we no longer need to define custom typings! The most recent versions of @types/react (v16.7.x) have the necessary types for hooks and will be installed properly when running create-react-app.

Now we can create a simple function component as provided by the React Hook documentation.

This component will render a button. Every time the button is clicked it will increment and display the count. Once theCounter component is added to the main App component we can run yarn start to see the example in the browser.

This is a basic example of getting started with React Hooks in a TypeScript app but provides the environment and typings to experiment with Hooks. Check out this repository for all of the above code with many more examples. React Hooks are yet another tool in your React tackle box! 🎣