Complete worked example
typescript
import { useReducer } from "react";
type Action = {type:"add";title:string}|{type:"reset"};
function reducer(state:string[],action:Action):string[]{return action.type === "reset" ? [] : [...state,action.title];}
export function Titles(){const [titles,dispatch]=useReducer(reducer,[]);return <button onClick={()=>dispatch({type:"add",title:"QA"})}>{titles.length}</button>;}- Reasoning
- The action union and immutable reducer connect dispatched events to valid next states.