Skip to content

Instantly share code, notes, and snippets.

@FocusThen
Created February 21, 2021 20:44
Show Gist options
  • Save FocusThen/6afac2fdba5a1ac71dfc848c895039c2 to your computer and use it in GitHub Desktop.
Save FocusThen/6afac2fdba5a1ac71dfc848c895039c2 to your computer and use it in GitHub Desktop.
React useState from scratch
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()
@Bhaumik-Tandan
Copy link

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