`as const` makes React hooks return real tuples

useState hands back a [value, setter] pair, so it seems reasonable to simply return it from our own hook:

import { useCallback, useState } from "react";

export function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn((value) => !value), []);

  return [on, toggle];
}

Everything looks fine, but when you use it, TypeScript shows typing error:

const [isOpen, toggleOpen] = useToggle();

toggleOpen();
// error TS2349: This expression is not callable.
//   Not all constituents of type 'boolean | (() => void)' are callable.
//     Type 'false' has no call signatures.

TypeScript doesn’t infer an array literal as a tuple. It infers [on, toggle] as an array of everything that can appear in it:

(boolean | (() => void))[]

So every element has the type boolean | (() => void). You can’t call the setter without narrowing and you can’t pass isOpen where a boolean is expected.

The fix is stupidly simple. Add as const to the return:

export function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn((value) => !value), []);

  return [on, toggle] as const;
}

Now the return type is inferred as a tuple:

readonly [boolean, () => void]

as const tells TypeScript to infer the narrowest type it can. For an array literal that means a readonly tuple with a fixed length, instead of an array. The readonly part doesn’t get in the way, because you only destructure the result.

A more explicit way is to annotate the return type, but you have to keep the annotation in sync with the body:

export function useToggle(initial = false): [boolean, () => void] {
← All notes