Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An explaination of how React Hooks work under-the-hood to persist data across function calls (AKA "renders" of FCs)
/**
* This is similar to how React tracks hook's data under-the-hood
*/
const state = [];
let idx = 0;
function useState(init) {
const id = ++idx;
state[id] = state[id] ?? {val: init};
return [
state[id].val,
(data => state[id].val = data)
]
}
function Test() {
const [data, setData] = useState(1);
console.log(data);
setData(data + 1)
}
Test() // 1
Test() // 2
Test() // 3
function Test() {
const a = 1;
console.log(a);
a++;
}
// Notice how these values don't persist between calls, like Hooks do
Test() // 1
Test() // 1
Test() // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment