React TypeScript
Author: Joel M Turner 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 parensReact.useState<boolean>(false);React.useRef<HTMLDivElement>(null);React.useCallback( function () { if (theMoon) { setSomethingAwesome(); } }, [theMoon],);Props
type FooProps = { children: React.ReactNode;};Components
// functionalconst Foo: React.FC<FooProps> = (props) => ()// classclass Foo extends React.Component<FooProps> {}emotion
const Foo = styled<FooProps>.div``;