Created
October 31, 2018 01:59
-
-
Save ryardley/e83bad1985740ab33b18fc578ec1957a to your computer and use it in GitHub Desktop.
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
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]; | |
} | |
// Our component code that uses hooks | |
function RenderFunctionComponent() { | |
const [firstName, setFirstName] = useState("Rudi"); // cursor: 0 | |
const [lastName, setLastName] = useState("Yardley"); // cursor: 1 | |
return ( | |
<div> | |
<Button onClick={() => setFirstName("Richard")}>Richard</Button> | |
<Button onClick={() => setFirstName("Fred")}>Fred</Button> | |
</div> | |
); | |
} | |
// This is sort of simulating Reacts rendering cycle | |
function MyComponent() { | |
cursor = 0; // resetting the cursor | |
return <RenderFunctionComponent />; // render | |
} | |
console.log(state); // Pre-render: [] | |
MyComponent(); | |
console.log(state); // First-render: ['Rudi', 'Yardley'] | |
MyComponent(); | |
console.log(state); // Subsequent-render: ['Rudi', 'Yardley'] | |
// click the 'Fred' button | |
console.log(state); // After-click: ['Fred', 'Yardley'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I see the problem with the
firstRun
variable too.The call of
useState("Rudi")
setsfirstRun
tofalse
, so next call ofuseState("Yardley")
won't push it'sinitialVal
to the state:I think it can be addressed by replacing the check of
firstRun
with the following check: