Two Rules of React Hooks

Hi, as we know the React hooks are new additions to React version 16.8, and hooks help us to use a state and other features without write a class. 

What exactly is a hook? well, hooks are basically a Javascript functions, and this functions have some rules, React provides a linter plugin ( is a tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs) will help us not to break the rules.

Rule 1

Do not call hooks inside loops, conditions, or nested functions. 

React relies on the order in which Hooks are called

 // 1. Use the name state variable
  const [name, setName] = useState('Mary');

  // 2. Use an effect for persisting the form
  useEffect(function persistForm() {
    localStorage.setItem('formData', name);
  });

  // 3. Use the surname state variable
  const [surname, setSurname] = useState('Poppins');

  // 4. Use an effect for updating the title
  useEffect(function updateTitle() {
    document.title = name + ' ' + surname;
  });

But the problem exist if we insert a hook inside a condition; this will break the rule. in this example the first render will be true but if the user make the condition to false at this point the we are affecting the order of the calls.

if (name !== '') {
    useEffect(function persistForm() {
      localStorage.setItem('formData', name);
    });
  }

So, instead we need to call the hooks at the top level of our React function doing this we ensure that Hooks are called in the same order each time a component renders.

Is ok if we insert conditions inside the hooks, like this: 

useEffect(function persistForm() {
    // We're not breaking the first rule anymore
    if (name !== '') {
      localStorage.setItem('formData', name);
    }
  });

So, in that case we are not breaking the rule.

Rule 2

  • Only call hooks from React functions, not from regular Javascript functions. 
  • Call Hooks from custom Hooks

By Criss.