RecipesChapter 10: TypeScript and React

Typing Custom Hooks

Recipe 10.2 from The TypeScript Cookbook

export const useToggle = (initialValue: boolean) => {
  const [value, setValue] = useState(initialValue);
  const toggleValue = () => setValue(!value);
  // here, we freeze the array to a tuple
  return [value, toggleValue] as const;
}
Open in TypeScript Playground →