Hooks in React follow a few fundamental rules to ensure they work correctly. These rules are enforced by React's linter plugin (eslint-plugin-react-hooks).
if (someCondition) {
const [state, setState] = useState(0); // Hook inside condition
}
const [state, setState] = useState(0); // Always at the top level
if (someCondition) {
console.log(state);
}
function someUtilityFunction() {
const [count, setCount] = useState(0); // Hooks inside a regular function
}
function MyComponent() {
const [count, setCount] = useState(0); // Hooks inside a functional component
}
use Prefix for Custom Hooksuse prefix (e.g., useMyHook).function useCustomHook() {
const [value, setValue] = useState(0);
return [value, setValue];
}
function customHook() { // No "use" prefix
const [value, setValue] = useState(0);
return [value, setValue];
}
React provides an ESLint plugin:
npm install eslint-plugin-react-hooks --save-dev
This will warn you if you break any Hook rules.