Skip to content

Instantly share code, notes, and snippets.

@FocusThen
Created February 21, 2021 20:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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()
@ArcN25
Copy link

ArcN25 commented Jan 30, 2024

Does reRender() work after u press F5 on browser?
Can u explain line 17?

@FocusThen
Copy link
Author

Does reRender() work after u press F5 on browser? Can u explain line 17?

  1. yea reRender just a function, when you refresh the page it works like normal.
  2. tuple [initValue, setValue] is created to represent the state and the function to update that state.

@Bhaumik-Tandan
Copy link

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

@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