React hook usage rules

Posted May 27, 20201 min read

React hook usage rules

  1. Use Hook only at the top level(Do not call Hook in loops, conditions or nested functions)
  2. Call Hook only in React functions(Do not call Hook in ordinary JavaScript functions)

Understand hook usage rules

Rule 2 Needless to say, only use state in react components
Rule 2, for the initial user, it may be a little unaccustomed, so let's talk about when this is the case, and then may not be confused about this

function RenderFunctionComponent() {
  const [firstName, setFirstName]= useState("Rudi");
  const [lastName, setLastName]= useState("Yardley");

    <Button onClick = {() => setFirstName("Fred")}> Fred </Button>

Use hook development

You can use the react-hooks plugin to enforce these rules and prompt in real time.