Last active
September 19, 2021 07:03
-
-
Save idiotWu/002be7d5bb2135d54416d80dac3d7bf8 to your computer and use it in GitHub Desktop.
Reimplement react hooks
This file contains 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
const hookMap = new WeakMap(); | |
let currentContext = null; | |
let currentIndex = 0; | |
function load(component) { | |
if (!hookMap.has(component)) { | |
hookMap.set(component, []); | |
} | |
currentContext = hookMap.get(component); | |
currentIndex = 0; | |
console.info('switched to context:', currentContext); | |
component(); | |
} | |
function createHook(initValue) { | |
const hook = { | |
value: initValue, | |
setValue(newValue) { | |
hook.value = newValue; | |
}, | |
} | |
return hook; | |
} | |
function useHook(initValue) { | |
if (!currentContext[currentIndex]) { | |
currentContext[currentIndex] = createHook(initValue); | |
} | |
const { value, setValue } = currentContext[currentIndex++]; | |
return [value, setValue]; | |
} | |
function ComponentA() { | |
const [count, setCount] = useHook(10); | |
console.log('[A] count:', count); | |
setCount(count + 1); | |
const [rnd, setRnd] = useHook(); | |
console.log('[A] rnd:', rnd); | |
setRnd(Math.random()); | |
} | |
function ComponentB() { | |
const [time, setTime] = useHook(Date.now()); | |
console.log('[B] time:', time); | |
setTime(Date.now()); | |
} | |
// test | |
load(ComponentA); | |
load(ComponentA); | |
load(ComponentA); | |
load(ComponentB); | |
load(ComponentB); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment