[사용 시기]
DOM 요소의 위치, 크기 조정이 필요할 때.
애니메이션 효과나 스크롤 위치 설정.
[차이점]
useEffect: 렌더링 이후 실행 (비동기).
useLayoutEffect: 렌더링 직전에 실행 (동기).
[사용 예시]
const FancyInput = React.forwardRef((props, ref) => {
const inputRef = React.useRef();
React.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
}));
return <input ref={inputRef} />;
});
function Parent() {
const ref = React.useRef();
return (
<div>
<FancyInput ref={ref} />
<button onClick={() => ref.current.focus()}>포커스</button>
</div>
);
}
function LayoutEffectExample() {
const divRef = React.useRef();
React.useLayoutEffect(() => {
console.log(divRef.current.offsetHeight);
}, []);
return <div ref={divRef}>레이아웃 확인</div>;
}
function App() {
const [isPending, startTransition] = React.useTransition();
const [count, setCount] = React.useState(0);
const handleClick = () => {
startTransition(() => {
setCount((c) => c + 1);
});
};
return (
<div>
<button onClick={handleClick}>클릭</button>
{isPending ? <p>로딩 중...</p> : <p>결과: {count}</p>}
</div>
);
}
function Component() {
const id = React.useId();
return (
<label htmlFor={id}>
입력창
<input id={id} />
</label>
);
}
function App({ value }) {
const deferredValue = React.useDeferredValue(value);
return <div>{deferredValue}</div>;
}