Skip to content

Instantly share code, notes, and snippets.

@idiotWu
Last active September 19, 2021 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idiotWu/002be7d5bb2135d54416d80dac3d7bf8 to your computer and use it in GitHub Desktop.
Save idiotWu/002be7d5bb2135d54416d80dac3d7bf8 to your computer and use it in GitHub Desktop.
Reimplement react hooks
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