🚀 프로젝트/따꼼

아이 등록 단계별 페이지 내 중복 코드 컴포넌트로 분리

seheej 2025. 3. 16. 16:33

1. 리팩토링 배경

RegisterChildInfo.tsxRegisterChildRecord.tsx 두 개의 파일에서 상단 네비게이션(뒤로 가기 버튼 + 제목)이 반복되고 있었다.

이러한 중복된 UI를 하나의 재사용 가능한 컴포넌트로 분리하면 유지보수가 쉬워지고, 코드 가독성이 높아진다. 따라서 StepNavigation.tsx라는 별도의 컴포넌트를 만들어 적용해 보았다.

 

2. 기존 코드 문제점

RegisterChildInfo.tsxRegisterChildRecord.tsx에서 상단 네비게이션 UI가 반복되고 있었다.

<div className="w-full px-6 py-2 flex items-center gap-6 mb-4 sm:hidden">
  <div className="relative">
    <button onClick={() => router.back()}>
      <Image src={PreIcon} alt="이전" />
    </button>
  </div>
  <div className="flex-1 text-center" style={{ transform: "translateX(-24px)" }}>
    <p className="text-base font-bold text-[#303030]">아이 등록하기</p>
  </div>
</div>

위 코드가 여러 파일에서 중복되어 유지보수가 어렵고, 변경이 필요할 때 일일이 수정해야 하는 문제가 발생했다.

 

3. 해결 방법

네비게이션 UI를 StepNavigation.tsx라는 별도의 컴포넌트로 분리하여 재사용성을 높였다.

"use client";

import { useRouter } from "next/navigation";
import Image from "next/image";
import PreIcon from "@/public/icon/preIcon.svg";

interface StepNavigationProps {
  title: string;
  onBack?: () => void;
}

const StepNavigation = ({ title, onBack }: StepNavigationProps) => {
  const router = useRouter();

  const handleBack = () => {
    if (onBack) {
      onBack();
    } else {
      router.back();
    }
  };

  return (
    <div className="w-full px-6 py-2 flex items-center gap-6 mb-4 sm:hidden">
      <div className="relative">
        <button onClick={handleBack}>
          <Image src={PreIcon} alt="이전" />
        </button>
      </div>
      <div className="flex-1 text-center" style={{ transform: "translateX(-24px)" }}>
        <p className="text-base font-bold text-[#303030]">{title}</p>
      </div>
    </div>
  );
};

export default StepNavigation;

 

 

4. 리팩토링 후 코드 적용

기존 파일에서 중복된 네비게이션 UI를 삭제하고, StepNavigation.tsx를 import하여 사용하도록 변경했다.

변경된 RegisterChildInfo.tsx

import StepNavigation from "@/components/common/StepNavigation";

const RegisterChildInfo = ({ onNext, childInfo }: RegisterChildInfoProps) => {
  return (
    <div className="container flex flex-col mx-auto justify-center max-w-[588px] mt-16">
      <StepNavigation title="아이 등록하기" />
      {/* 기존 코드 유지 */}
    </div>
  );
};

 

변경된 RegisterChildRecord.tsx

import StepNavigation from "@/components/common/StepNavigation";

const RegisterChildRecord = ({ child, onPrev, onComplete }: RegisterChildRecordProps) => {
  return (
    <div className="container flex flex-col mx-auto justify-center max-w-[792px] mt-16">
      <StepNavigation title="아이 등록하기" onBack={onPrev} />
      {/* 기존 코드 유지 */}
    </div>
  );
};

 

 

5. 리팩토링 효과

중복 코드 제거 → UI가 변경될 때 한 곳만 수정하면 됨
재사용성 증가StepNavigation.tsx를 다른 페이지에서도 활용 가능
가독성 향상 → 각 파일이 본래 기능에 집중할 수 있도록 정리됨

 

 

6. 결론

이처럼 중복된 UI를 분리하여 재사용 가능한 컴포넌트로 만드는 것은 유지보수와 가독성을 높이는 데 큰 도움이 된다. 이번 리팩토링을 통해 앞으로도 컴포넌트의 재사용성을 고려하며 개발하는 습관을 길러야겠다고 느꼈다.