Rules of Using Hooks
There are certain rules we must follow while using Hooks to avoid surprises. For the hooks, there are two simple rules:
Only call hooks at the top level;
Only call hooks from React functions.
Top-level means directly inside the React component, and outside of any other code blocks, for example, loops or conditions. The following code shows valid and invalid cases:
js991234567891011121314151617function Main(props) {// Correctconst [ text, updateText ] = useState("Example");// Incorrectif(true) {const [ example, setExample ] = useState(0);}// Incorrectfor(let i = 0; i < 10; i++) {useEffect(() => {console.log(text);});}return <p>{text}</p>;}
Apart from that, calling React hooks in functions other than React components is also invalid:
js99123456789101112function randomFunction() {// Incorrectconst [ count, setCount ] = useState(0);return 1;}function Main(props) {// Correct, as this function represents a componentconst [ text, updateText ] = useState("Example");return <p>{text}</p>;}
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 6. Kapitel 4
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal