Performance: Multiple effects in a component
This affects the interaction responsiveness and rendering speed by controlling how many times React runs side effects and triggers updates.
function MyComponent() { React.useEffect(() => { // fetch data // update document title // add event listener }, []); return <div>Content</div>; }
function MyComponent() { React.useEffect(() => { // fetch data }, []); React.useEffect(() => { // update document title }, []); React.useEffect(() => { // add event listener }, []); return <div>Content</div>; }
| Pattern | Effect Executions | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple separate useEffect calls | 3 | 3 | High | [X] Bad |
| Single combined useEffect call | 1 | 1 | Low | [OK] Good |
useEffect hooks in a React component?useEffect hooks allow you to separate different side effects logically in a component.useEffect hooks in a React functional component?useEffect hook takes a function and a dependency array as arguments, separated by a comma.useEffect hooks should be called one after another, each with its own function and dependency array, ending with semicolons.function Example({ count }) {
useEffect(() => {
console.log('Effect A:', count);
}, [count]);
useEffect(() => {
console.log('Effect B: component mounted');
}, []);
return <div>Count: {count}</div>;
}count = 5?useEffect hooks run after the first render. They run in the order they appear in code.useEffect logs 'Effect A: 5', the second logs 'Effect B: component mounted'. So logs appear in code order.function Demo({ value }) {
useEffect(() => {
console.log('Effect 1:', value);
}, [value]);
useEffect(() => {
console.log('Effect 2');
});
return <div>Value: {value}</div>;
}useEffect has a dependency array [value], so it runs only when value changes.useEffect has no dependency array, so it runs after every render, which might be unintended.useEffect hooks?Pass the test and this pattern moves unknown