How to call a method immediately after state is updated or component is re-rendered?
Learn how to handle post-state updates in React using useEffect and useLayoutEffect hooks.
Question
How to call a method immediately after state is updated or after a component is re-rendered in React?
Answer
In React functional components, use useEffect to handle logic after a state change or render.
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count updated:', count);
}, [count]);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
âś… useEffect runs after render when count changes.
âś… Add [count] to dependencies to trigger only when that state updates.
Using useLayoutEffect
If you need to measure or manipulate DOM before the paint:
useLayoutEffect(() => {
console.log('DOM updated but before paint');
}, [count]);
Real-World Example
- Scroll to a ref after data loads
- Trigger animations post-render
- Sync localStorage after state updates
Quick Practice
Build a counter that logs the new value and scrolls to the top after each update.
Summary
Use useEffect(() => {...}, [state]) for post-update logic and useLayoutEffect for pre-paint DOM synchronization.
Why doesn’t setState have a callback like class components?
In functional components, you handle post-update logic in useEffect.
When should I use useLayoutEffect?
When you need to run logic before the browser paints the UI (like measuring DOM).
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.