[A project ] study(9) use-funnel

dev kyu·2025년 2월 11일

project

목록 보기
11/15

use-funnel이란,

모바일 네비게이션에 최적화된 단계별 상태 관리 라이브러리야.
@use-funnel

📍핵심 설명

  • useFunnel은 엘리베이터 버튼**이라고 생각해봐!
    단계를 배열(steps)로 관리하고, nextStep()과 previousStep()을 사용하여 손쉽게 단계 이동을 할 수 있도록 도와주는 훅이야.

  • useFunnel의 핵심 기능
    • 여러 단계를 배열로 저장 (steps)
    • nextStep()을 호출하면 다음 단계로 이동
    • previousStep()을 호출하면 이전 단계로 이동
    • 현재 단계를 step으로 반환 (step === steps[currentIndex])
    • 마지막 단계(isLastStep), 첫 번째 단계(isFirstStep) 여부 확인 가능

### 🔍 use-funnel의 사용 예제 **1️⃣ use-funnel 설치**
패키지 매니저설치 명령어
pnpmpnpm add @use-funnel/react-router-dom
pnpm add @use-funnel/next
pnpm add @use-funnel/react-navigation-native
pnpm add @use-funnel/browser
yarnyarn add @use-funnel/react-router-dom
yarn add @use-funnel/next
yarn add @use-funnel/react-navigation-native
yarn add @use-funnel/browser

❗ 하지만, use-funnel 패키지는 공식 라이브러리가 아니므로, 직접 구현해야 함!

2️⃣ useFunnel.ts 생성 (hooks/useFunnel.ts)

import { useState } from 'react';

const useFunnel = (steps: string[]) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  const nextStep = () => {
    setCurrentIndex((prev) => (prev < steps.length - 1 ? prev + 1 : prev));
  };

  const previousStep = () => {
    setCurrentIndex((prev) => (prev > 0 ? prev - 1 : prev));
  };

  return {
    step: steps[currentIndex],
    nextStep,
    previousStep,
    isLastStep: currentIndex === steps.length - 1,
    isFirstStep: currentIndex === 0,
  };
};

export default useFunnel;

🙌 단계를 배열(steps)로 관리, nextStep(), previousStep()을 이용하여 이동

3️⃣ SignupPage.tsx에서 useFunnel 적용

import useFunnel from '@src/hooks/useFunnel';
import AgreementList from '@src/components/AgreementList';
import NameInputStep from '@src/components/NameInputStep';
import PhoneInputStep from '@src/components/PhoneInputStep';
import SignupSuccessPage from '@src/components/SignupSuccessPage';

const SignupPage = () => {
  const { step, nextStep, previousStep } = useFunnel([
    'agreement',
    'name-input',
    'phone-input',
    'success'
  ]);

  return (
    <div>
      {step === 'agreement' && <AgreementList onNext={nextStep} />}
      {step === 'name-input' && <NameInputStep onNext={nextStep} />}
      {step === 'phone-input' && <PhoneInputStep onNext={nextStep} />}
      {step === 'success' && <SignupSuccessPage onNext={nextStep} />}

      {/* 이전 단계 버튼 */}
      {step !== 'agreement' && (
        <button onClick={previousStep} className="mt-4 px-4 py-2 bg-gray-300 rounded">
          이전 단계
        </button>
      )}
    </div>
  );
};

export default SignupPage;

🚀 진짜 쉬운 설명

useFunnel 적용 순서
1️⃣ 프로젝트 구조 설정 → hooks/, components/, pages/ 폴더 구성
2️⃣ 커스텀 훅 useFunnel.ts 생성 → 단계별 관리 (nextStep(), previousStep())
3️⃣ SignupPage.tsx에서 useFunnel 사용 → 단계별 UI 적용
4️⃣ 단계 이동 로직 추가 → 버튼 클릭 시 nextStep() & previousStep() 실행


✏️ 더 알아가기

  • 어떤 경우에 어떤 방식이 좋을까?

1️⃣ useState가 더 적합한 경우
모든 체크박스가 한 화면에서 한 번에 보여야 하는 경우
필수/선택 항목이 단계별로 구분될 필요가 없는 경우
체크박스를 사용자가 자유롭게 조작할 수 있어야 하는 경우

2️⃣ useFunnel이 더 적합한 경우
필수 항목을 먼저 체크하고, 이후 선택 항목을 보여줘야 하는 경우
체크박스를 단계를 나눠서 점진적으로 사용자에게 보여주고 싶은 경우
폼(회원가입, 동의 과정)이 여러 단계로 나뉘어 있는 경우

✔️ useState : 체크박스를 항상 한 화면에 보이게 하고, 개별적으로 체크할 때 적합
✔️ useFunnel : 체크 단계를 진행하면서 필요한 체크박스만 보이게 하고 싶을 때 적합

체크박스가 한 번에 다 보여야 하면 useState, 단계별로 나눠서 진행해야 하면 useFunnel을 선택하면 돼!

  • 한눈에 비교하기
비교 항목useState 사용useFunnel 사용
체크박스 상태 관리개별 true/false 값을 직접 조작step 상태를 변경하여 관리
사용 방식setState로 개별 상태 업데이트nextStep()으로 단계 이동
체크박스 표시 방식모든 체크박스가 한 번에 보임단계별로 필요한 체크박스만 표시
제어 방식모든 체크박스를 개별적으로 조작 가능특정 단계에서 특정 체크박스만 활성화 가능
단계 이동없음 (모든 체크박스가 항상 표시됨)nextStep(), previousStep() 사용 가능
가독성상태가 많아질수록 관리가 복잡해짐논리적으로 단계를 나눠서 깔끔하게 관리 가능
유지보수새로운 체크박스 추가 시 useState 구조 수정 필요단계 배열(steps)에 추가하면 쉽게 관리 가능
profile
dev kyu

0개의 댓글