Performance: Creating custom hooks
Custom hooks affect component rendering speed and bundle size by reusing logic efficiently and avoiding unnecessary re-renders.
function useCounter() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(id); }, []); return count; } function Component() { const count = useCounter(); return <div>{count}</div>; }
function Component() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(id); }, []); return <div>{count}</div>; } // Repeated in multiple components without abstraction
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated logic in components | Multiple effect setups | Multiple reflows per component | Higher paint cost due to repeated updates | [X] Bad |
| Custom hook with stable dependencies | Single effect setup reused | Single reflow per update | Lower paint cost with fewer updates | [OK] Good |
import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}useWindowWidth() return when used inside a component?import { useState, useEffect } from 'react';
function useCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1);
});
return count;
}useFetch that fetches data from a URL and returns { data, loading, error }. Which approach correctly handles loading state and errors inside the hook?Pass the test and this pattern moves unknown