useEffect
- used to schedule a function to run after the render is committed to the screen
- runs asynchronously after the component has rendered and the browser has painted to the screen
- How do you run async functions inside??
- What is cleanup function with an example?
useLayoutEffect
- same timing as
useEffect, but it fires synchronously immediately after all DOM mutations
- runs synchronously after React has performed all DOM mutations, but before the browser has painted those changes
useLayoutEffect can hurt performance. Prefer useEffect when possible.
- Use when your effect needs to read from the DOM and/or perform immediate DOM mutations that should be reflected synchronously.
- Uses:
- measuring elements or
- performing layout-dependent calculations that require up-to-date DOM dimensions
function LayoutEffectComponent() {
const ref = useRef(null);
useLayoutEffect(() => {
// This effect runs synchronously after DOM updates
console.log(ref.current.getBoundingClientRect());
}, []); // Runs once after initial render
return <div ref={ref}>Layout Effect Example</div>;
}