React TypeScript

Author: Published Updated

How do you type React hooks, refs, and event handlers in TypeScript?

Add generic type parameters directly to React hooks (useState, useRef, useCallback) and type event handlers with React's built-in event types. This page collects the TypeScript patterns I use most when wiring up typed React components.


Hooks

// add type before parens
React.useState<boolean>(false);
React.useRef<HTMLDivElement>(null);
React.useCallback(
function () {
if (theMoon) {
setSomethingAwesome();
}
},
[theMoon],
);

Props

type FooProps = {
children: React.ReactNode;
};

Components

// functional
const Foo: React.FC<FooProps> = (props) => ()
// class
class Foo extends React.Component<FooProps> {}

emotion

const Foo = styled<FooProps>.div``;

< Mobx Storybook >