#들어가며
Compound Component 패턴으로 Navigation Bar를 만들었다. 스크롤 다운하면 네비게이션이 위로 숨겨지고, 스크롤 업하면 다시 나타나는 기능을 추가했다.
그런데 이상한 일이 벌어졌다. 네비게이션이 숨겨질 때 페이지 전체 콘텐츠가 함께 위로 이동한다. Footer까지 같이 움직인다. 왜 이런 현상이 발생할까?
#문제의 코드
// NavigationBar.tsx
function NavigationBarRoot({ children }: NavigationBarRootProps) {
return (
<NavigationBarContext.Provider value={contextValue}>
<header
className={cn(
"sticky top-0 z-50",
"transition-transform duration-300",
isNavVisible ? "translate-y-0" : "-translate-y-full",
)}
>
{children} {/* ❌ 모든 children이 header 안에 들어감 */}
</header>
</NavigationBarContext.Provider>
);
}
레이아웃에서 사용:
// layout.tsx
<NavigationBarRoot>
<NavigationBarBar>...</NavigationBarBar>
<NavigationBarMegaMenu />
<NavigationBarMobileMenu />
<PageWrapper>{children}</PageWrapper> {/* ❌ header 안에 포함됨 */}
<Footer /> {/* ❌ header 안에 포함됨 */}
</NavigationBarRoot>
#원인: 구조적 문제
다이어그램을 불러오는 중입니다.Compound Component 구조 문제 · 원본 다운로드
Compound Component 패턴에서 Root 컴포넌트가 모든 children을 감싸는 header를 렌더링하고 있다.
NavigationBarRoot
└── <header sticky translate-y>
├── NavigationBarBar ✅ header 안에 있어야 함
├── NavigationBarMegaMenu ✅ header 안에 있어야 함
├── PageWrapper ❌ header 밖에 있어야 함
└── Footer ❌ header 밖에 있어야 함
header에 translate-y: -100%를 적용하면 그 안의 모든 children이 함께 이동한다. PageWrapper와 Footer도 header 안에 있으니까 같이 움직인다.
#의도한 구조 vs 실제 구조
// 의도한 구조
<header sticky translate-y>
<nav>네비게이션만</nav>
</header>
<main>컨텐츠</main> // header 밖!
// 실제 구조 (문제)
<header sticky translate-y>
<nav>네비게이션</nav>
<main>컨텐츠</main> // header 안에 포함됨!
</header>
#해결책: 구조 분리
다이어그램을 불러오는 중입니다.해결된 구조 · 원본 다운로드
Root 컴포넌트에서 header를 렌더링하지 않고, 별도의 Header 컴포넌트를 만든다.
#NavigationBarRoot - Context만 제공
function NavigationBarRoot({ children }: NavigationBarRootProps) {
const [isNavVisible, setIsNavVisible] = useState(true);
const lastScrollYRef = useRef(0);
const handleScroll = useCallback(() => {
const currentScrollY = window.scrollY;
if (currentScrollY < SCROLL_THRESHOLD) {
setIsNavVisible(true);
} else if (currentScrollY > lastScrollYRef.current) {
setIsNavVisible(false);
} else {
setIsNavVisible(true);
}
lastScrollYRef.current = currentScrollY;
}, []);
useEffect(() => {
window.addEventListener("scroll", handleScroll, { passive: true });
return () => window.removeEventListener("scroll", handleScroll);
}, [handleScroll]);
return (
<NavigationBarContext.Provider value={{ ...contextValue, isNavVisible }}>
{children} {/* ✅ header 없이 children만 반환 */}
</NavigationBarContext.Provider>
);
}
#NavigationBarHeader - sticky header 담당 (새로 추가)
function NavigationBarHeader({ children }: NavigationBarHeaderProps) {
const { isNavVisible, closeMenu } = useNavigationBarContext();
return (
<header
className={cn(
"w-full sticky top-0 z-50",
"bg-background/80 backdrop-blur-md border-b border-border/50",
"transition-transform duration-300 ease-out",
isNavVisible ? "translate-y-0" : "-translate-y-full",
)}
onMouseLeave={closeMenu}
>
{children}
</header>
);
}
#수정된 레이아웃
// layout.tsx
<NavigationBarRoot>
{/* Sticky Header - 네비게이션만 포함 */}
<NavigationBarHeader>
<NavigationBarBar>
<NavigationBarBrand>Tech Blog</NavigationBarBrand>
<NavigationBarDesktopNav />
<NavigationBarMobileToggle />
</NavigationBarBar>
<NavigationBarMegaMenu />
</NavigationBarHeader>
<NavigationBarMobileMenu />
{/* Main Content - Header 밖에 위치 */}
<PageWrapper>{children}</PageWrapper> {/* ✅ header 밖 */}
<Footer /> {/* ✅ header 밖 */}
</NavigationBarRoot>
#Before vs After
#Before
NavigationBarRoot
└── header (sticky + translate-y)
├── Bar
├── MegaMenu
├── MobileMenu
├── PageWrapper ← 문제!
└── Footer ← 문제!
#After
NavigationBarRoot (Context만 제공)
├── NavigationBarHeader (sticky + translate-y)
│ ├── Bar
│ └── MegaMenu
├── MobileMenu
├── PageWrapper ← header 밖!
└── Footer ← header 밖!
#Compound Component 패턴에서의 교훈
#Root는 Context만 제공하는 게 좋다
// ❌ Root가 wrapper 렌더링
function Root({ children }) {
return (
<Context.Provider>
<div className="wrapper">{children}</div>
</Context.Provider>
);
}
// ✅ Root는 Context만, wrapper는 별도 컴포넌트
function Root({ children }) {
return <Context.Provider>{children}</Context.Provider>;
}
function Wrapper({ children }) {
return <div className="wrapper">{children}</div>;
}
이렇게 분리하면:
- children 중 일부만 wrapper에 포함시킬 수 있다
- 레이아웃 유연성이 높아진다
- sticky, position 등 레이아웃 영향을 주는 스타일을 세밀하게 제어할 수 있다
#스크롤 감지 최적화
// state 대신 ref 사용 → 불필요한 리렌더링 방지
const lastScrollYRef = useRef(0);
const handleScroll = useCallback(() => {
// lastScrollYRef.current 사용
lastScrollYRef.current = currentScrollY; // 리렌더링 없음
}, []);
lastScrollY를 state로 관리하면 스크롤할 때마다 리렌더링이 발생한다. ref로 관리하면 값만 저장하고 렌더링은 트리거하지 않는다.
#정리
Compound Component에서 Root가 직접 wrapper를 렌더링하면, 모든 children이 그 wrapper 안에 포함된다. sticky + translate-y 같은 레이아웃 스타일을 적용하면 의도치 않게 전체 콘텐츠가 영향받는다.
해결책은 Root에서 wrapper 렌더링을 분리하는 것이다. Root는 Context만 제공하고, wrapper는 별도의 컴포넌트로 만든다. 이렇게 하면 필요한 children만 wrapper에 포함시킬 수 있다.