Performance: Dynamic rendering triggers
Dynamic rendering triggers affect page load speed and interaction responsiveness by causing repeated layout recalculations and re-renders during user interactions or data changes.
Jump into concepts and practice - no test required
export default function Search() { const [query, setQuery] = React.useState(''); const handleChange = React.useCallback( e => { const value = e.target.value; clearTimeout(window.debounceTimeout); window.debounceTimeout = setTimeout(() => setQuery(value), 300); }, [] ); return <input type="text" defaultValue={query} onChange={handleChange} />; }
export default function Search() { const [query, setQuery] = React.useState(''); return ( <input type="text" value={query} onChange={e => setQuery(e.target.value)} /> ); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Immediate state update on every input | High (many nodes updated) | High (1 per keystroke) | High (frequent repaint) | [X] Bad |
| Debounced input state update | Low (batched updates) | Low (few reflows) | Low (less repaint) | [OK] Good |
| Filtering large list on every render | High (many nodes re-rendered) | High (multiple reflows) | High (heavy repaint) | [X] Bad |
| Memoized filtering with useMemo | Medium (only filtered nodes) | Low (minimal reflows) | Medium (repaints only on filter change) | [OK] Good |
useStateuseState creates a state variable that, when updated, triggers a re-render of the component.useEffect runs side effects but does not itself trigger re-renders; useRef holds mutable values without causing re-renders; useContext shares data but depends on context changes.useState -> Option CuseState?setCount(5); correctly calls the setter function. Assigning directly to setCount or count is invalid.import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<>
Count: {count}
setCount(count + 1)}>Increment
</>
);
}setCount(count + 1), increasing count by 1.import { useState } from 'react';
export default function Example() {
const [value, setValue] = useState('');
function handleClick() {
value = 'Updated';
}
return (
<>
{value}
Update
</>
);
}handleClick assigns directly to value, which is a state variable and read-only.setValue('Updated') to trigger re-render.import { useState, useEffect } from 'react';
export default function UserProfile() {
const [user, setUser] = useState(null);
useEffect(() => {
let isMounted = true;
fetch('/api/user')
.then(res => res.json())
.then(data => {
if (isMounted) setUser(data);
});
return () => { isMounted = false; };
}, []);
if (!user) return <p>Loading...</p>;
return <p>Hello, {user.name}!</p>;
}useEffect with empty dependency array runs once on mount, triggering dynamic rendering when data arrives.isMounted flag prevents setting state if the component unmounts before fetch completes, avoiding memory leaks or errors.