Skip to content

Instantly share code, notes, and snippets.

@tonis2
Created November 8, 2018 11:09
Show Gist options
  • Save tonis2/b03f4c5e65f861d3f6ae2f0aa5a79576 to your computer and use it in GitHub Desktop.
Save tonis2/b03f4c5e65f861d3f6ae2f0aa5a79576 to your computer and use it in GitHub Desktop.
Create hook
Thanks to ///https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e
let state = [];
let setters = [];
let firstRun = true;
let cursor = 0;
function createSetter(cursor) {
return function setterWithCursor(newVal) {
state[cursor] = newVal;
};
}
// This is the pseudocode for the useState helper
export function useState(initVal) {
if (firstRun) {
state.push(initVal);
setters.push(createSetter(cursor));
firstRun = false;
}
const setter = setters[cursor];
const value = state[cursor];
cursor++;
return [value, setter];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment