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() |
Does reRender() work after u press F5 on browser? Can u explain line 17?
- yea reRender just a function, when you refresh the page it works like normal.
- tuple [initValue, setValue] is created to represent the state and the function to update that state.
But I think there is a problem here the state does not accepts updater function or creator function
Like you can’t do something like;
setState((prev)=>prev+1)) here
The setState should be something like: states[id][0] = newValue instanceof Function ? newValue(states[id][0]) : newValue;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does reRender() work after u press F5 on browser?
Can u explain line 17?