Performance: Reusing logic with hooks
This affects interaction responsiveness and rendering efficiency by reducing unnecessary component updates and re-renders.
function useCounter() { const [count, setCount] = React.useState(0); const increment = React.useCallback(() => setCount(c => c + 1), []); return { count, increment }; } function ComponentA() { const { count, increment } = useCounter(); return <button onClick={increment}>Count: {count}</button>; } function ComponentB() { const { count, increment } = useCounter(); return <button onClick={increment}>Count: {count}</button>; }
function ComponentA() { const [count, setCount] = React.useState(0); const increment = () => setCount(count + 1); return <button onClick={increment}>Count: {count}</button>; } function ComponentB() { const [count, setCount] = React.useState(0); const increment = () => setCount(count + 1); return <button onClick={increment}>Count: {count}</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated state logic in components | Multiple independent states | Multiple reflows per component update | Higher paint cost due to repeated renders | [X] Bad |
| Custom hook with memoized callbacks | Single state logic reused | Single reflow per state update | Lower paint cost due to fewer renders | [OK] Good |
ExampleComponent renders?function useToggle(initial) {
const [on, setOn] = React.useState(initial);
const toggle = () => setOn(!on);
return [on, toggle];
}
function ExampleComponent() {
const [isOn, toggle] = useToggle(false);
React.useEffect(() => {
console.log(isOn);
}, [isOn]);
return Toggle;
}function useCounter() {
const [count, setCount] = React.useState(0);
function increment() {
count = count + 1;
}
return { count, increment };
}useFetch that fetches data from a URL and returns loading state, data, and error. Which approach correctly reuses logic and handles updates safely?function useFetch(url) {
const [data, setData] = React.useState(null);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
React.useEffect(() => {
setLoading(true);
fetch(url)
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}Pass the test and this pattern moves unknown