codedamn

Lazy state initialization with useState

Created by Codedamn about a year ago

0

No description provided

3 Comments

    0

    i can't understand this concept ...

    0

    same man i also can't understand this concept.. Sometimes mr. mehul forgets his own description of course which is: beginner friendly.. I really can't get the json.parse example..

    @harshthakur12

    Harsh Thakur

    @harshthakur12

    3

    This was not easy to understand. So, I am trying to make it easy for other people to understand by this example. I want to focus on function initialise below which is a computationally expensive function.

    const Lazy = () => {
      function initialise(){
        console.log("This is computationally expensive.")
        return 0;
      }
      const [state, setState] = useState(initialise());
      return (
        <>
          <div>state:{state}</div>
          <button onClick={()=>setState((value)=>value+1)}>Click me</button>
        </>
      )
    }
    export default Lazy;
    

    There are two ways to initialise this function:

    1. const [state, setState] = useState(initialise());
    2. const [state, setState] = useState(()=>initialise());

    If you initialise the function with first method then the function will be called each time the re-render happens. You can verify this in console as everytime you click the button you will see the log "This is computationally expensive." Since, we don't want to call this computationally expensive process again and again, so we will initialise it with second method(lazy initialisation). This time you will not see the console log "This is computationally expensive." everytime you click the button (only one or two time depending on whether you are using strictMode or not) which verifies that the function is not being called every time the re-render happens.

    @shresth

    Shresth Raj

    @shresth

Your comment