Created
February 21, 2021 20:44
-
-
Save FocusThen/6afac2fdba5a1ac71dfc848c895039c2 to your computer and use it in GitHub Desktop.
React useState from scratch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
let callCount = -1 | |
let states = [] | |
function useState(initValue) { | |
const id = ++callCount | |
if (states[id]) return states[id] | |
const setValue = (newValue) => { | |
states[id][0] = newValue | |
reRender() | |
} | |
let tuple = [initValue, setValue] | |
states.push(tuple) | |
return tuple | |
} | |
const App = () => { | |
// creating variable | |
const [counter, setCounter] = useState(0); | |
return ( | |
<section> | |
<h2>{counter}</h2> | |
<button onClick={()=> setCounter(counter + 1)}>+</button> | |
<button onClick={()=> setCounter(counter - 1)}>-</button> | |
</section> | |
) | |
} | |
function reRender() { | |
// reset callCounter | |
callCount = -1 | |
ReactDOM.render(<App />, document.getElementById('root')); | |
} | |
// initial render | |
reRender() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The setState should be something like: states[id][0] = newValue instanceof Function ? newValue(states[id][0]) : newValue;