Middle
What rules exist for writing hooks in React?
sobes.tech AI
Answer from AI
- Call hooks only at the top level of functional components or inside other custom hooks. Hooks cannot be called inside loops, conditions, or nested functions.
- Call hooks only inside React functional components. Do not call them in regular JavaScript functions or class components.
- Using
useCallbackfor memoizing functions anduseMemofor memoizing computations helps optimize performance. - Use
useEffectfor side effects (loading data, subscriptions, etc.), specifying a dependency array to control when the effect runs. - Maintain the order of hook calls on every render. React relies on this order to correctly associate state and effects.
- Use stable dependencies in the dependency arrays of
useEffect,useCallback,useMemo. Do not pass objects or functions that are recreated on every render unless necessary. - Create custom hooks to reuse state logic between components. Custom hook names should start with
use.
// Correct example: calling hooks at the top level
function MyComponent() {
const [count, setCount] = useState(0); // Call at the top level
useEffect(() => { // Call at the top level
document.title = `You clicked ${count} times`;
}, [count]); // Dependency array
const handleClick = useCallback(() => { // Call at the top level
setCount(c => c + 1);
}, []); // Memoized function
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>
Click me
</button>
</div>
);
}
// Incorrect example: calling hook inside a condition
// function MyComponentWithBadHook() {
// if (someCondition) {
// const [count, setCount] = useState(0); // INCORRECT: call inside condition
// }
// // ...
// }
// Incorrect example: calling hook inside a loop
// function MyComponentWithAnotherBadHook() {
// for (let i = 0; i < 5; i++) {
// const [value, setValue] = useState(i); // INCORRECT: call inside loop
// }
// // ...
// }