Reimplementing the useState function

In order to get a better understanding of how Hooks work internally, we are going to reimplement the useState Hook from scratch. However, we are not going to implement it as an actual React Hook, but as a simple JavaScript function—just to get an idea of what Hooks are actually doing.

Please note that this reimplementation is not exactly how React Hooks work internally. The actual implementation is similar, and thus, it has similar constraints. However, the real implementation is much more complicated than what we will be implementing here.

We are now going to start reimplementing the State Hook:

  1. First, we copy the code from chapter1_2, where we are going to replace the current useState Hook with our own implementation.
  2. Open src/App.js and remove the import of the Hook by removing the following line:
import React, { useState } from 'react'

Replace it with these lines of code:

import React from 'react'
import ReactDOM from 'react-dom'
We are going to need ReactDOM in order to force rerendering of the component in our reimplementation of the useState Hook. If we used actual React Hooks, this would be dealt with internally.
  1. Now, we define our own useState function. As we already know, the useState function takes the initialState as an argument:
function useState (initialState) {
  1. Then, we define a value, where we will store our state. At first, this value will be set to initialState, which is passed as an argument to the function:
    let value = initialState
  1. Next, we define the setState function, where we will set the value to something different, and force the rerendering of our MyName component:
    function setState (nextValue) {
value = nextValue
ReactDOM.render(<MyName />, document.getElementById('root'))
}
  1. Finally, we return the value and the setState function as an array:
    return [ value, setState ]
}

The reason why we use an array, and not an object, is that we usually want to rename the value and setState variables. Using an array makes it easy to rename the variables through destructuring:

const [ name, setName ] = useState('')

As we can see, Hooks are simple JavaScript functions that deal with side effects, such as setting a stateful value.

Our Hook function uses a closure to store the current value. The closure is an environment where variables exist and are stored. In our case, the function provides the closure, and the value variable is stored within that closure. The setState function is also defined within the same closure, which is why we can access the value variable within that function. Outside of the useState function, we cannot directly access the value variable unless we return it from the function.

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

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