useStep Hook
Build a useStep custom hook that tracks a clamped step counter with next/prev/reset controls, then wire it to a small stepper UI with disabled-aware buttons and a live status readout.
Implement a reusable useStep(maxStep) custom hook inside App.tsx and use it to drive a small multi-step UI.
The hook manages a step value that starts at 1 and is always clamped to the inclusive range [1, maxStep]. It returns an object:
{
step: number; // current step (1-based)
next: () => void; // advance one step, never above maxStep
prev: () => void; // go back one step, never below 1
reset: () => void; // jump back to step 1
canNext: boolean; // true when step < maxStep
canPrev: boolean; // true when step > 1
}The App component calls useStep with a fixed maxStep of 4 and renders:
- A live
role="status"region showingStep X of N(e.g. "Step 1 of 4"). - A Next button, disabled when
canNextis false (already on the last step). - A Prev button, disabled when
canPrevis false (on the first step). - A Reset button that returns to step 1.
Clicking Next past the last step or Prev before the first step must be a no-op (the value stays clamped), and the buttons must reflect canNext/canPrev so the user can't even trigger an out-of-range move.
Requirements
- Implement useStep(maxStep) inside App.tsx returning { step, next, prev, reset, canNext, canPrev }.
- step starts at 1 and is always clamped to the inclusive range [1, maxStep].
- next() advances by one but never above maxStep; prev() goes back by one but never below 1; reset() returns to step 1.
- canNext is true only when step < maxStep; canPrev is true only when step > 1.
- Render a role="status" region with the text "Step X of N" reflecting the current step and maxStep.
- Render Next, Prev, and Reset buttons; Next is disabled when !canNext and Prev is disabled when !canPrev.
Hints (3)
- Track the current step with useState initialized to 1. Derive canNext/canPrev from step rather than storing them in separate state.
- In next/prev use the functional updater form and Math.min/Math.max to keep the value inside [1, maxStep]: e.g. setStep(s => Math.min(maxStep, s + 1)).
- Disable the Next button with disabled={!canNext} and Prev with disabled={!canPrev} so out-of-range clicks are impossible from the UI.
Topics
- React
- React Hooks
Asked at
MakeMyTrip · Ola · Zomato · Zoho · Delhivery · Groww
