Using a global variable

As we have learned, the value is stored within the closure that is defined by the useState function. Every time the component rerenders, the closure is reinitialized, which means that our value will be reset. To solve this, we need to store the value in a global variable, outside of the function. That way, the value variable will be in the closure outside of the function, which means that when the function gets called again, the closure will not be reinitialized.

We can define a global variable as follows:

  1. First, we add the following line (in bold) above the useState function definition:
let value

function useState (initialState) {
  1. Then, we replace the first line in our function with the following code:
       if (typeof value === 'undefined') value = initialState

Now, our useState function uses the global value variable, instead of defining the value variable within its closure, so it will not be reinitialized when the function gets called again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.132