Prerequisite: This article assumes that you have already used hooks

What happens when you use set

So the first thing we know is that we’re going to change the state, we’re going to compare it to the DOM, and if the DOM changes, we’re going to do dom rendering so let’s take a look at the characteristics of useState

Simple implementation of useState

Code is not much, interested in their own knock again

The details of the useState

Look first at the contents of the App component and then at the implementation of useState

Multiple USestates are supported

Note: index should be 0 before the second execution of App; You might say, well, I tried, but I could have done it after the second time! Uh… Set = async; render = async; set = async; render = async

import React from 'react';
import ReactDOM from 'react-dom';

let state = []// Used to store values passed by useState
let index = 0
const nodeList = [] // Used to store the node returned from each App call
const useState = (initValue) = > {
  const currentIndex = index // Write down the current subscript, since index needs +1 to store the next useState
  state[index] = state[index] === undefined ? initValue : state[index]
  const setState = (newState) = > {
    state[currentIndex] = newState
    index = 0
    ReactDOM.render(<App />.document.getElementById('root'));
    console.log(nodeList)
  }
  console.log(` myUseState n:${state}`)
  index += 1
  return [state[currentIndex], setState]
}

const App = () = > {
  const [n, setN] = useState(0)
  const [m, setM] = useState(0)
  console.log(N ` App:${n}`)
  const component = (// Add an intermediate variable to record the node returned by App each time
    <div>
      {n}
      <button onClick={()= > { setN(n + 1) }}>+1</button>
      {m}
      <button onClick={()= > { setM(m + 1) }}>+1</button>
    </div>
  )
  nodeList.push(component)// Save the node for easy viewing
  return (component)
}

ReactDOM.render(<App />.document.getElementById('root'));
Copy the code

The disadvantage of useState

UseState stores and sets by performing sequential assignment subscripts each time, so you can’t use useState with operations like if, which sometimes and sometimes don’t change the order of the array