0Pricing
React Native Academy · 강의

양식 상태를 활용한 다단계 양식

상태에 단계 카운터를 두어 긴 회원가입 양식을 여러 단계로 나누고, 다음 단계로 넘어가기 전에 현재 단계의 필드만 검증합니다.

양식 상태를 활용한 다단계 양식은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is a Multi-Step Form?

A multi-step form breaks a long registration or checkout flow into discrete, manageable steps — typically 2 to 5 screens. Each step focuses on a related group of fields, reducing cognitive load and improving completion rates compared to a single long scroll. Common examples include onboarding wizards, address-plus-payment checkout flows, and multi-stage profile setup.

Sharing One Form Instance Across Steps

The key to a multi-step form with react-hook-form is to create one useForm instance for the entire form and pass control and errors down as props to each step component. This keeps all field values and validation state in one place. Values entered on step 1 remain available when the user reaches step 3, and submitting the final step accesses the complete form data.

interface RegisterForm {
  name: string;
  email: string;
  password: string;
  phone: string;
  city: string;
}

export default function RegisterScreen() {
  const [step, setStep] = React.useState(1);
  const form = useForm<RegisterForm>({ defaultValues: { name: '', email: '', password: '', phone: '', city: '' } });

  return (
    <View style={styles.container}>
      {step === 1 && <Step1AccountInfo form={form} />}
      {step === 2 && <Step2ContactDetails form={form} />}
      {step === 3 && <Step3Review form={form} onSubmit={handleFinalSubmit} />}
    </View>
  );
}

Defining Step Component Props

Each step component receives the form instance as a prop. Define a TypeScript type for the prop using UseFormReturn from react-hook-form. This gives the step component access to control, formState.errors, trigger, and watch — all the tools needed to render and validate its own subset of fields.

import type { UseFormReturn } from 'react-hook-form';

interface StepProps {
  form: UseFormReturn<RegisterForm>;
  onNext?: () => void;
}

export function Step1AccountInfo({ form, onNext }: StepProps) {
  const { control, formState: { errors } } = form;
  // Render only name, email, and password fields
}

Validating Only the Current Step

Before advancing to the next step, validate only the fields on the current step using form.trigger(['fieldA', 'fieldB']). This runs validation on the specified fields and returns a Promise that resolves to true if all are valid. If any fail, the errors appear and the user cannot advance until they are fixed. Fields on later steps are not validated yet.

async function handleNext() {
  const step1Fields: (keyof RegisterForm)[] = ['name', 'email', 'password'];
  const isValid = await form.trigger(step1Fields);
  if (isValid) {
    setStep(2);
  }
  // If invalid, formState.errors is populated for the listed fields
}

Progress Indicator UI

Add a visual progress bar or step indicator at the top of the screen so users know how far along they are. Calculate progress as (currentStep / totalSteps) * 100. A simple progress bar using an animated View width gives clear feedback and sets expectations about how much more is required before they can complete the form.

const TOTAL_STEPS = 3;

function ProgressBar({ current }: { current: number }) {
  const progress = (current / TOTAL_STEPS) * 100;
  return (
    <View style={styles.progressContainer}>
      <View style={[styles.progressFill, { width: progress + '%' }]} />
    </View>
  );
}

// Usage:
<ProgressBar current={step} />

Navigating Between Steps

Use a step counter in useState to track the current step. 'Next' buttons validate the current step's fields with trigger before incrementing the step. 'Back' buttons decrement the step without re-validating. Always disable the 'Next' button or show a loading spinner while async validation (like username availability checks) is in progress.

const { formState: { isValidating } } = form;

function NavigationButtons() {
  return (
    <View style={styles.navRow}>
      {step > 1 && (
        <Button title='Back' onPress={() => setStep((s) => s - 1)} />
      )}
      {step < TOTAL_STEPS ? (
        <Button
          title={isValidating ? 'Checking...' : 'Next'}
          onPress={handleNext}
          disabled={isValidating}
        />
      ) : (
        <Button title='Submit' onPress={form.handleSubmit(onFinalSubmit)} />
      )}
    </View>
  );
}

Reviewing Entered Data on the Final Step

The final step is often a review screen where users confirm their entries before submitting. Use form.getValues() to read all field values and display them in a summary list. This gives users one last chance to catch typos before the data is sent to the server, reducing support requests and user errors.

function Step3Review({ form, onSubmit }: StepProps) {
  const values = form.getValues();

  return (
    <ScrollView>
      <Text>Review your information:</Text>
      <Text>Name: {values.name}</Text>
      <Text>Email: {values.email}</Text>
      <Text>Phone: {values.phone}</Text>
      <Text>City: {values.city}</Text>
      <Button title='Confirm and Register' onPress={onSubmit} />
    </ScrollView>
  );
}

Using formState.isSubmitting

formState.isSubmitting is true while handleSubmit's async callback is running. Use it to disable the submit button and show a loading spinner during the API call. This prevents double-submissions when the user taps quickly and gives clear feedback that the form is being processed.

const { formState: { isSubmitting } } = form;

<Button
  title={isSubmitting ? 'Submitting...' : 'Confirm and Register'}
  onPress={form.handleSubmit(onFinalSubmit)}
  disabled={isSubmitting}
/>

Persisting Step Data Across Navigation

If users navigate away from the multi-step form and return later, use Zustand or React Navigation's route params to preserve the current step and partially filled form data. Combine this with react-hook-form's reset(savedValues) to restore the form to where the user left off. This dramatically reduces form abandonment on mobile.

// On unmount or navigation away:
useEffect(() => {
  return () => {
    const currentValues = form.getValues();
    useFormDraftStore.getState().saveDraft(currentValues, step);
  };
}, []);

// On mount, restore if draft exists:
useEffect(() => {
  const draft = useFormDraftStore.getState().draft;
  if (draft) {
    form.reset(draft.values);
    setStep(draft.step);
  }
}, []);

Keyboard Navigation Between Fields

On mobile, tapping 'Next' on the keyboard should move focus to the next input within a step. Use useRef to hold refs for each TextInput and call ref.current.focus() in the onSubmitEditing callback of each input. Set returnKeyType='next' on intermediate fields and 'done' on the last field of each step.

const emailRef = React.useRef<TextInput>(null);
const passwordRef = React.useRef<TextInput>(null);

<TextInput
  placeholder='Full Name'
  returnKeyType='next'
  onSubmitEditing={() => emailRef.current?.focus()}
/>
<TextInput
  ref={emailRef}
  placeholder='Email'
  returnKeyType='next'
  onSubmitEditing={() => passwordRef.current?.focus()}
/>
<TextInput
  ref={passwordRef}
  placeholder='Password'
  returnKeyType='done'
  onSubmitEditing={handleNext}
  secureTextEntry
/>

Handling Back Navigation Safely

When the user presses the hardware back button on Android or swipes back on iOS, handle it to decrement the step counter instead of leaving the screen entirely. Use useFocusEffect with a BackHandler to intercept the hardware back event. If the user is on step 1, allow normal navigation back to the previous screen.

import { BackHandler } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';

useFocusEffect(
  React.useCallback(() => {
    const handler = BackHandler.addEventListener('hardwareBackPress', () => {
      if (step > 1) {
        setStep((s) => s - 1);
        return true; // prevent default back navigation
      }
      return false; // allow default (exit screen)
    });
    return () => handler.remove();
  }, [step])
);

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: one useForm instance shared across all steps keeps form data and validation state unified, trigger with specific field names validates only the current step before advancing, and formState.isSubmitting disables the submit button during the final API call to prevent duplicate submissions. Next up we explore submitting and resetting forms.

자주 묻는 질문

“양식 상태를 활용한 다단계 양식” 강의는 무료인가요?

네 — “양식 상태를 활용한 다단계 양식” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“양식 상태를 활용한 다단계 양식”에서 뭘 배우나요?

상태에 단계 카운터를 두어 긴 회원가입 양식을 여러 단계로 나누고, 다음 단계로 넘어가기 전에 현재 단계의 필드만 검증합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“양식 상태를 활용한 다단계 양식” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Controller로 react-hook-form 설정하기
  2. 검증 규칙과 오류 메시지
  3. 양식 상태를 활용한 다단계 양식
  4. 양식 제출 및 초기화
← React Native Academy(으)로 돌아가기