Performance: Why custom hooks are used
Custom hooks affect component rendering efficiency and code reuse, impacting interaction responsiveness and bundle size.
function useCounter() { const [count, setCount] = React.useState(0); React.useEffect(() => { console.log('Count changed:', count); }, [count]); return [count, setCount]; } function ComponentA() { const [count, setCount] = useCounter(); return <button onClick={() => setCount(count + 1)}>{count}</button>; } function ComponentB() { const [count, setCount] = useCounter(); return <button onClick={() => setCount(count + 1)}>{count}</button>; }
function ComponentA() { const [count, setCount] = React.useState(0); React.useEffect(() => { console.log('Count changed:', count); }, [count]); return <button onClick={() => setCount(count + 1)}>{count}</button>; } function ComponentB() { const [count, setCount] = React.useState(0); React.useEffect(() => { console.log('Count changed:', count); }, [count]); return <button onClick={() => setCount(count + 1)}>{count}</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated state logic in components | Multiple state hooks per component | Multiple re-renders on state change | Higher paint cost due to redundant updates | [X] Bad |
| Custom hook for shared logic | Single state hook reused | Fewer re-renders due to consistent logic | Lower paint cost with optimized updates | [OK] Good |
function useCounter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(timer);
}, []);
return count;
}
function Counter() {
const count = useCounter();
return {count};
}function useData() {
const [data, setData] = React.useState(null);
fetch('https://api.example.com/data')
.then(res => res.json())
.then(json => setData(json));
return data;
}
function App() {
const data = useData();
return <div>{JSON.stringify(data)}</div>;
}Pass the test and this pattern moves unknown