Track the current wizard step by id as the step list changes
Checkout flows and onboarding forms walk the user through a list of steps. The list is often dynamic: a “Shipping” step disappears when the cart only has digital items, or a “Verify phone” step appears after the user enters a number. Implement a React hook, useWizard, that tracks the current step of such a flow by its id and keeps the user in the right place when the list changes.
function useWizard(steps: string[]): {
step: string | null; // id of the current step
index: number; // its position in steps
total: number; // steps.length
isFirst: boolean;
isLast: boolean;
next: () => void;
back: () => void;
goTo: (id: string) => void;
reset: () => void;
}
steps is an array of unique step ids, in display order.
index 0).next() moves to the following step. On the last step it does nothing.back() moves to the previous step. On the first step it does nothing.goTo(id) jumps to the step with that id. An id that is not in steps is ignored.reset() goes back to the first step.next() twice in one click handler moves two steps.steps array can change between renders, and callers usually pass an inline array (a new array on every render). That must not cause render loops. When it changes:
index may change.steps is empty, return step: null, index: -1, total: 0, and false for isFirst and isLast. The actions do nothing. If the hook mounted with an empty list and steps arrive later, start on the first step.const wizard = useWizard(['cart', 'shipping', 'payment', 'review']);
// step 'cart', index 0, total 4, isFirst true
wizard.next(); // 'shipping', index 1
wizard.goTo('review'); // 'review', index 3, isLast true
wizard.next(); // still 'review'
wizard.goTo('gift-wrap'); // ignored, still 'review'
wizard.back(); // 'payment'
// On 'payment' (index 2) of ['cart', 'shipping', 'payment', 'review'].
// The cart becomes digital-only, so the component passes:
// ['cart', 'payment', 'review']
// The user stays on 'payment', which is now index 1.
// On 'shipping' (index 1) of ['cart', 'shipping', 'payment', 'review'].
// The component passes ['cart', 'payment', 'review'].
// 'shipping' is gone, so the step now at index 1 is shown: 'payment'.
ReactDOM.flushSync.Object.assign(window, { useWizard }); below “Do not edit below this line”. The tests use it to call your hook.