Performance: Lifecycle mapping with hooks
This concept affects how React components manage rendering and updates, impacting interaction responsiveness and rendering speed.
function MyComponent() { React.useEffect(() => { console.log('Effect runs once on mount'); }, []); return <div>Hello</div>; }
function MyComponent() { React.useEffect(() => { // expensive operation console.log('Effect runs every render'); }); return <div>Hello</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Effect without dependencies | N/A | Multiple reflows per render | High paint cost due to repeated updates | [X] Bad |
| Effect with empty dependency array | N/A | Single reflow on mount | Minimal paint cost | [OK] Good |
| State update inside effect without dependencies | N/A | Infinite reflows | Continuous paint blocking UI | [X] Bad |
| Multiple separate effects | N/A | Multiple reflows | Moderate paint cost | [!] OK |
| Combined effects in one hook | N/A | Single reflow | Lower paint cost | [OK] Good |
componentDidMount and componentDidUpdate?useEffect hook runs code after rendering, replacing lifecycle methods like componentDidMount and componentDidUpdate.useState manages state, useContext accesses context, and useRef stores mutable values. Only useEffect runs side effects after render.useEffect?[] as the second argument to useEffect makes it run only once after the first render (component mount).useEffect(() => { /* code */ }); runs after every render. useEffect(() => { /* code */ }, true); runs after every render since non-array dependencies are ignored. useEffect(() => { /* code */ }, null); with null also runs after every render as it's not an array.count state changes?function Counter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('Count is', count);
}, [count]);
return setCount(count + 1)}>Increment;
}count changes because count is in the dependency array.count is 0, so it logs 'Count is 0'. After clicking the button, count becomes 1, triggering the effect again and logging 'Count is 1'.useEffect and suggest the fix:function Timer() {
React.useEffect(() => {
const id = setInterval(() => console.log('Tick'), 1000);
}, []);
return <div>Timer</div>;
}useEffect that calls clearInterval(id) to stop the interval on unmount.useEffect?useEffect that calls controller.abort() to cancel the fetch if unmount happens early.Pass the test and this pattern moves unknown