import { useCallback, useMemo, useState } from "react"; /** * * @kind 12-State */ export const useStep = (steps: number) => { const [currentStep, setCurrentStep] = useState(1); const isLast = useMemo(() => currentStep + 1 <= steps, [currentStep, steps]); const isFirst = useMemo(() => currentStep - 1 >= 1, [currentStep]); const setStep = useCallback( (step: number | ((prev: number) => number)) => { const nextStep = step instanceof Function ? step(currentStep) : step; if (nextStep >= 1 && nextStep <= steps) { setCurrentStep(nextStep); return; } throw new Error("Step not valid"); }, [steps, currentStep], ); const next = useCallback(() => { if (isLast) { setCurrentStep((step) => step + 1); } }, [isLast]); const previous = useCallback(() => { if (isFirst) { setCurrentStep((step) => step - 1); } }, [isFirst]); const reset = useCallback(() => { setCurrentStep(1); }, []); return { step: currentStep, next, previous, isLast, isFirst, setStep, reset, }; };