Importance of the order of hooks in a component

Let us see the importance of order of hooks using an example :

JavaScript
import { useState, useEffect } from "react";
function App() 
{
   const [name,setName] = useState('Mohit')
   useEffect( () =>{
    localStorage.setItem('Name',name)
   })
   const [surname,setSurname] = useState('Sharma')
   useEffect( () =>{
    document.title = name +' ' + surname
   })
}
export default App;

Explanation : In the above code, we are using two useState hooks and two useEffect hooks. After the first render, the react preserves the order of hooks and from the next renders, react expects the same order of hooks. As we can see, the hooks in the above code are obeying all the rules of hooks so this code works well and we can see the output in the local storage.

Order of hooks in the above code :

useState( )
useEffect( )
useState( )
useEffect( )

If we try to disturb or change this order, Let us see how it violates the rules of react and understand the importance of order of hooks using the below code :

JavaScript
import { useState, useEffect } from "react";
function App() {
    const [name, setName] = useState('Mohit')
    if (name != '') {
        useEffect(() => {
            localStorage.setItem('Name', name)
        })
    }
    const [surname, setSurname] = useState('Sharma')
    useEffect(() => {/*  */}
        document.title = name + ' ' + surname
    })
}
export default App;

Output :

Importance of the order of hooks in a component

Here comes the importance of the order of hooks, as we added the useEffect hook in a if condition, In the first render the name was β€˜Mohit’ So the condition in the if statement was true and the order of hooks in the first render was as follows :

1.useState     βœ…
2.useEffect βœ…
3.useState βœ…
4.useEffect βœ…

In the second render, if the name was set to β€˜ β€˜ (empty) , it makes the condition in the if statement became false and this skipped the useEffect hook inside the if statement. So the order of hooks in the second order was as follows :

1. useState   βœ…
2.useEffect ❌//This hook was skipped
3.useState ❌ //Fails to read the state variable
4.useEffect ❌ //Fails to replace the effect

In the previous render, the order of hooks were useState followed by useEffect but in the next render the order changed to useState followed by useState which caused a confusion to react because it expected a useEffect after the useState but got useState hook where the react didn’t have any idea what to return and all the next hooks in the order got skipped.

To avoid these errors, we can use the conditional statements inside the hooks where the order of hooks is not disturbed and it is preserved shown in the below code :

JavaScript
import { useState, useEffect } from "react";
function App() {
    const [name, setName] = useState('Mohit')
    useEffect(() => {
        if (name != '') {
            localStorage.setItem('Name', name)
        }
    })
    console.log("Hooks Rules Violated")
    const [surname, setSurname] = useState('Sharma')
    useEffect(() => {
        document.title = name + ' ' + surname
    })
}
export default App;

Output:

Importance of the order of hooks in a component

In the above code, we have used the conditional statement inside the useEffect which is obeying the rules of hooks making it to preserve the order of hooks in each render.



What is the importance of the order of hooks in a component?

While using hooks in a component, we should not call hooks inside loops, conditions, or nested functions. Instead, we should always use hooks at the top level of a function or a component. Also, we should ensure that the hooks are called in the same order in each render. In this article, we will discuss the importance of the order of hooks in a component.

Similar Reads

Rules of Hooks in React

Hooks should be only called at the top level of a component – Hooks should not be called inside loops, conditions, nested functions, or any JavaScript functions.Hooks must be called in the same order – React preserves the order of hooks, so we must make sure that the hooks are called in the same order across renders.Hooks should be called only from react components – Hooks should not be called from regular JavaScript functions or event handlers. It should be called only from react components...

Why are these rules important?

As we discussed the rules of hooks, are very important and will lead to different errors if not followed. These rules will avoid bugs and ensure that our hooks work as expected....

Importance of the order of hooks in a component

Let us see the importance of order of hooks using an example :...