React Foundations · TypeScript

Typing hook state

Typing hook state

useState(0) infers number, but infer from a value that could be more than one thing and the state's type drifts with it. Name the type yourself with a type argument:

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

Now count is a number and setCount accepts a number or an updater. The same argument types an object state: useState<CounterState>({ count: 0 }) gives every read and write the shape of CounterState.

A reducer is typed through its own signature. Declare the state and the action, then annotate the reducer's parameters with them:

interface CounterState {
  count: number;
}

type CounterAction = { type: 'add'; amount: number } | { type: 'reset' };

function reducer(state: CounterState, action: CounterAction): CounterState {
  switch (action.type) {
    case 'add':
      return { count: state.count + action.amount };
    case 'reset':
      return { count: 0 };
  }
}

useReducer reads those types from reducer, so state is a CounterState and dispatch accepts only a CounterAction. Switch on action.type and each branch narrows to that action's fields — action.amount exists only on add.

Your job is to type hook state in App.tsx.

Challenge

useState and useReducer both need their state type. Export an App component from App.tsx that keeps a counter in a useReducer. Declare an interface CounterState with a count, and a CounterAction union of { type: 'add'; amount: number } and { type: 'reset' }. Annotate the reducer with those types. Read a step from useState<number>(2) and render a paragraph showing the count, plus an Add button that dispatches add with that step.

The Test clicks Add and expects the count to read 2. The starter renders a fixed count, so the Test fails.

App.tsx
export function App() {
  return (
    <div>
      <p>0</p>
      <button>Add</button>
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.