
useFunnel이란?💠useFunnel 은 단계적인 Form 흐름을 쉽게 관리할 수 있는 React Hook!
💠 단순한 useState(step) 방식이 아니라, 각 단계를 key로 관리할 수 있게 설계됨
useState 사용했을 때const [step, setStep] = useState(1);
return (
<div>
{step === 1 && <Step1/>}
{step === 2 && <Step2/>}
{step === 3 && <Step3/>}
<button onClick={()=>setStep(step -1)}>이전</button>
<button onClick={()=>setStep(step +1)}>다음</button>
</div>
);
♦️step 을 숫자로 관리해야해서 이게 무슨 단계인지 가독성이 떨어진다
♦️ 조건문을 계속 추가해야해서 코드가 길어진다
♦️ 상태가 많아질수록 관리가 어려움
import { useFunnel, createFunnelSteps } from '@use-funnel/browser';
const steps = createFunnelSteps()
.extends('step1')
.extends('step2')
.extends('step3')
.build();
export default function ExampleForm() {
const funnel = useFunnel({
id: 'example',
steps,
initial: {
step: 'step1',
context: {},
},
});
return (
<div>
<funnel.Render
step1={({ history }) => (
<div>
<h1>Step 1</h1>
<button onClick={() => history.push('step2')}>다음</button>
</div>
)}
step2={({ history }) => (
<div>
<h1>Step 2</h1>
<button onClick={() => history.back()}>이전</button>
<button onClick={() => history.push('step3')}>다음</button>
</div>
)}
step3={() => <h1>Step 3</h1>}
/>
</div>
);
}
💠step을 숫자가 아니라 이름(key)로 관리 가능
💠history.push('다음단계'), history.back()을 이용하여 단계 이동 쉽게 처리
💠funnel.Render를 이용하여 각 단계별 UI를 자동으로 관리할 수 있음.
💠context를 활용해서 각 단계에서 입력한 데이터를 자동으로 저장 가능
| useState(step) 방식 | useFunnel 방식 | |
|---|---|---|
| 단계 관리 | setStep(step + 1) | history.push('nextStep') |
| 단계 렌더링 | if (step === 1) {...} | <funnel.Render>로 자동 관리 |
| 단계 상태 관리 | 숫자로 직접 관리 (1,2,3) | key 기반으로 관리 (step1, step2) |
| 이전 단계 | setStep(step - 1) 직접 관리 | history.back() 자동 제공 |
| 입력 값 저장 | useState로 개별 저장 | context로 자동 저장 |
💠단계가 1-2개뿐일 땐 useState를 사용해도 좋지만, 단계가 여러 개이고, 단계 이름이 중요한 경우에는 useFunnel을 사용하는게 유용하다!
💠특히나 단계 이동을 쉽게 구현할 수 있고 각 단계에서 입력한 데이터를 자동으로 저장해주는 이점이 있다