Skip to content
jshacks.dev
TypeScript

Type useState with a union

Pass a union to the useState generic so state holds only valid values, and the setter rejects anything else. Works with React 19 and TypeScript 5.

1 min read
Summarize in AI

useState('idle') infers string, so setStatus('typo') compiles. Giving the hook a union of the real states closes that.

SaveButton.tsxTSX
import { useState } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';

type Status = 'idle' | 'saving' | 'saved';

function SaveButton() {
  const [status, setStatus] = useState<Status>('idle');

  return (
    <button onClick={() => setStatus('saving')} disabled={status !== 'idle'}>
      {status}
    </button>
  );
}

console.log(renderToStaticMarkup(<SaveButton />));
Text
<button>idle</button>

useState<Status>('idle') fixes the state type to the union, so the setter accepts 'idle', 'saving' and 'saved' and nothing else, and status !== 'idle' is checked against real values. The server render shows the initial state and drops disabled, which is false. See the React docs on typing state.

Add the generic when the initial value is narrower than the type you want, such as useState<User | null>(null), where the inferred type would be null only. When the initial value already carries the right type, as with useState(0), leave it off. A union of string literals is cheap, and it also makes a switch on status exhaustive.

Also inFrameworks
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.