// init a state balance with value 666 // get state using balance // set state using setBalance method const [balance, setBalance] = useState(666); Javascript already provides a state abstraction, and react provides a function render to rerender a component. Let's build our useState upon these abstraction. let state; function useState(initialValue) { state = state || initialValue; function setter(newState) { state = newState; render(<App />, document.getElementById('root')); } return [state, setter]; }
setBalance(777); First render, the if statement is true, it executes asprevious: const [balance, setBalance] = useState(666); // state = [666], cursor = 1 // balance = state[0] // setBalance = (newState) => state[0] = newState //...
const [name, setName] = useState('handsome'); // state = [666, 'handsome'], cursor = 2 // name = state[1] // setBalance = (newState) => state[1] = newState //... After setBalance is called, if become false and rerender: // When we call setter: setBalance(777); // state = [777, 'handsome'], cursor = 0, rerender