The power of React Hooks allows us to manage reusable and composable state in our React components, without the need for class components or global state (such as Redux). Combining that with the flexibility of TypeScript interfaces, there are several different methods we can use to model our component state and context in a type-safe way.
In this post I will illustrate some of the benefits to using typescript strict mode with React Hooks and hope that you will consider using it for your TypeScript+React projects. Seemingly trivial things such as avoiding the Any type and ensuring you always define a return type will allow the type system to catch your mistakes before they can become runtime errors. This is especially helpful when debugging state management in React, where tracking down runtime errors can be particularly challenging.
Our goal will be to explore some examples of state management using React Hooks (specifically
useContext) while maintaining strict typing using TypeScript. In addition to providing type safety to our hooks and state data, types act as living documentation which provide clarity around how the application’s state is managed.