Middle
What are the rules for writing hooks in React?
sobes.tech AI
Answer from AI
- Hooks are called only at the top level of a component or another hook. You cannot call hooks inside loops, conditions, or nested functions.
- Hooks are called only inside functional React components or inside other custom hooks. You cannot call hooks in classes or regular JavaScript functions.
These rules ensure that React can correctly associate calls to useState and useEffect with the state and effects during each render.
There are also best practices and "unofficial" rules:
- Use the
useprefix for custom hooks. This convention helps clearly identify hooks. - Try to adhere to the single responsibility principle. Each hook should solve a specific task.
- Test custom hooks separately. Use libraries like
@testing-library/react-hooks.
// Correct: useState is called at the top level of the component
function MyComponent() {
const [count, setCount] = useState(0);
// ...
}
// Correct: useState is called at the top level of a custom hook
function useCounter() {
const [count, setCount] = useState(0);
// ...
return { count, setCount };
}
// Incorrect: useState is called inside a condition
function MyComponent() {
if (someCondition) {
const [count, setCount] = useState(0); // Error!
}
// ...
}
// Incorrect: useState is called inside a loop
function MyComponent() {
for (let i = 0; i < 5; i++) {
const [count, setCount] = useState(0); // Error!
}
// ...
}