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.
useState('idle') infers string, so setStatus('typo') compiles. Giving the hook a union of the real states closes that.
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 />));<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.