Dmytro Morar
TypeScript

Typing React components

Type React props and hooks to keep state and APIs predictable.

Props

type ButtonProps = { label: string; onClick?: () => void };
const Button = ({ label, onClick }: ButtonProps) => (
  <button onClick={onClick}>{label}</button>
);

useState

const [count, setCount] = React.useState<number>(0);

useRef

const inputRef = React.useRef<HTMLInputElement>(null);

Custom hook

function useFetch<T>(url: string): [T | null, boolean] {
  const [data, setData] = React.useState<T | null>(null);
  const [loading, setLoading] = React.useState(true);
  return [data, loading];
}

On this page