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
- Host: GitHub
- URL: https://github.com/anupamkhosla/reactusestatecustom
- Owner: AnupamKhosla
- Created: 2023-06-11T13:09:59.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-06-11T13:15:11.000Z (almost 2 years ago)
- Last Synced: 2025-01-16T06:58:09.400Z (5 months ago)
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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/objectconst 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();
```