packagesreacthooksuseIsomorphicLayoutEffect

useIsomorphicLayoutEffect

서버사이드 렌더링(SSR)과 클라이언트 환경에서 모두 안전하게 동작하는 useLayoutEffect입니다.

Return

  • 클라이언트 환경: useLayoutEffect 반환
  • 서버 환경: useEffect 반환 (SSR 경고 방지)

Usage

import { useIsomorphicLayoutEffect } from '@teamsparta/react';
 
function Example() {
  useIsomorphicLayoutEffect(() => {
    // DOM 측정이나 업데이트가 필요한 코드
    const elementHeight = element.getBoundingClientRect().height;
    // ...
  }, []);
 
  return <div>예제 컴포넌트</div>;
}

Example

요소 크기 측정

function ResizeAware() {
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const elementRef = useRef<HTMLDivElement>(null);
 
  useIsomorphicLayoutEffect(() => {
    if (!elementRef.current) return;
 
    const rect = elementRef.current.getBoundingClientRect();
    setDimensions({
      width: rect.width,
      height: rect.height,
    });
  }, []);
 
  return (
    <div ref={elementRef}>
      크기: {dimensions.width} x {dimensions.height}
    </div>
  );
}

애니메이션 동기화

function AnimatedComponent() {
  const [isVisible, setIsVisible] = useState(false);
 
  useIsomorphicLayoutEffect(() => {
    if (isVisible) {
      // DOM이 업데이트된 직후, 애니메이션 시작 전에 실행
      element.style.opacity = '1';
      element.style.transform = 'translateY(0)';
    }
  }, [isVisible]);
 
  return <div className="animated-element">애니메이션 요소</div>;
}