import { useCallback, useMemo, useState } from 'react'; interface UseWizardReturn { currentStep: number; nextStep: () => void; prevStep: () => void; goToStep: (step: number) => void; isFirstStep: boolean; isLastStep: boolean; totalSteps: number; } /** * Manages the state of a multi-step wizard component. * It provides a simple API to navigate between steps. * @param totalSteps - The total number of steps in the wizard. * @returns An object containing the current wizard state and navigation methods. * @example * const { currentStep, nextStep, prevStep, isLastStep } = useWizard(3); */ export const useWizard = (totalSteps: number): UseWizardReturn => { const [currentStep, setCurrentStep] = useState(1); const nextStep = useCallback(() => { setCurrentStep((step) => { if (step < totalSteps) { return step + 1; } return step; }); }, [totalSteps]); const prevStep = useCallback(() => { setCurrentStep((step) => { if (step > 1) { return step - 1; } return step; }); }, []); const goToStep = useCallback( (step: number) => { if (step > 0 && step <= totalSteps) { setCurrentStep(step); } }, [totalSteps] ); const isFirstStep = currentStep === 1; const isLastStep = currentStep === totalSteps; return useMemo( () => ({ currentStep, nextStep, prevStep, goToStep, isFirstStep, isLastStep, totalSteps, }), [currentStep, nextStep, prevStep, goToStep, isFirstStep, isLastStep, totalSteps] ); };