DEV Community

desgh white
desgh white

Posted on

Building a Multi-Step Form That Survives Page Refreshes

A three-step registration form where the user loses all input on a browser refresh is a conversion killer. The standard SPA approach — hold state in a React/Vue store — evaporates on reload. You need a persistence layer that the user never thinks about.

sessionStorage as the default

Write each step's data to sessionStorage on every input change, and hydrate from it on mount:

function usePersisted<T>(key: string, initial: T): [T, (v: T) => void] {
  const stored = sessionStorage.getItem(key);
  const [val, setVal] = useState<T>(stored ? JSON.parse(stored) : initial);
  const persist = (v: T) => { setVal(v); sessionStorage.setItem(key, JSON.stringify(v)); };
  return [val, persist];
}
Enter fullscreen mode Exit fullscreen mode

sessionStorage survives refreshes but not new tabs — which is the right scope for a registration flow.

Step validation

Validate each step before persisting, not just before submission. This prevents the user from refreshing into an invalid state:

function saveStep(step: number, data: StepData) {
  const errors = validate(step, data);
  if (errors.length) return errors;
  sessionStorage.setItem(`reg_step_${step}`, JSON.stringify(data));
  return [];
}
Enter fullscreen mode Exit fullscreen mode

Clearing on completion

After successful submission, clear all step keys and redirect. A registration flow on a site like Millioner that spans multiple pages of personal details must not leave that data in storage after the form is submitted.

Edge case: back button

If the user submits step 3 and then hits the browser back button, they see step 2 with stale data. Intercept popstate and either clear the form or redirect to a confirmation page:

window.addEventListener('popstate', () => {
  if (isSubmitted()) window.location.replace('/welcome');
});
Enter fullscreen mode Exit fullscreen mode

Takeaway

Persist form state on change, not on submit. Validate on persist, not on render. Clear on completion, not on navigation. Three rules that make multi-step forms reliable.

Top comments (0)