An open API service indexing awesome lists of open source software.

https://github.com/anupamkhosla/reactusestatecustom

Simplified reverse engineering of useState hook in react
https://github.com/anupamkhosla/reactusestatecustom

Last synced: 3 months ago
JSON representation

Simplified reverse engineering of useState hook in react

Awesome Lists containing this project

README

        

# reactUseStateCustom
Simplified reverse engineering of useState hook in react

### Demo: https://jsfiddle.net/fx4Ltdzm/

#### Complete hooks reverse engineering https://medium.com/swlh/learn-by-implementing-reacts-usestate-and-useeffect-a-simplified-overview-ea8126705a88

#### My Code:

```
const manualRerender = () => {
hookCount = -1; //recount total hook initializations on every render
root.render();
}

let hookCount = -1;
const states = {}; //hooks array/object

const TheuseState = (value) => {
const id = ++hookCount; //every hook call increases the hook count
const setValue = (newValue) => {
states[id][0] = newValue;
console.log(states);
manualRerender();
}
if (states[id] == undefined) { //first render
states[id] = [value, setValue];
}
else { //later renders don't get _value from TheuseState(_value)
states[id] = [states[id][0], setValue];
}
const state = states[id];
return state;
}

function App(props) {
const [count, setCount] = TheuseState(1);
//console.log([count, setCount]);
const [msg, setMsg] = TheuseState("Bye");
//console.log([msg, setMsg]);
console.log(states);
return (


Anupam khosla Counter


setCount(count+1)}>+++

{count}


setCount(count-1)}>---




setMsg(msg+msg)}>{msg}

);
}

const root = ReactDOM.createRoot(document.getElementById("app"));
root.render();
```