Created
November 8, 2018 11:09
-
-
Save tonis2/b03f4c5e65f861d3f6ae2f0aa5a79576 to your computer and use it in GitHub Desktop.
Create hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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