Created
November 26, 2019 13:52
-
-
Save tiagonevestia/faddce66b3d57862e27e643acc2aaf3b 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
// function useState(initialValue) { | |
// var _val = initialValue; | |
// function state() { | |
// return _val; | |
// } | |
// function setState(newVal) { | |
// _val = newVal; | |
// } | |
// return [state, setState]; | |
// } | |
const MyReact = (function() { | |
let hooks = [], | |
currentHook = 0; | |
return { | |
render(Component) { | |
const Comp = Component(); | |
Comp.render(); | |
currentHook = 0; // reset | |
return Comp; | |
}, | |
useEffect(callback, depArray) { | |
const hasNoDeps = !depArray; | |
const deps = hooks[currentHook]; | |
const hasChangedDeps = deps | |
? !depArray.every((el, i) => { | |
return el === deps[i]; | |
}) | |
: true; | |
if (hasNoDeps || hasChangedDeps) { | |
callback(); | |
hooks[currentHook] = depArray; | |
} | |
currentHook++; | |
}, | |
useRef(initialValue) { | |
return this.useState({ current: initialValue })[0]; | |
}, | |
useState(initialValue) { | |
hooks[currentHook] = hooks[currentHook] || initialValue; | |
const setStateIndex = currentHook; | |
const setState = newState => (hooks[setStateIndex] = newState); | |
return [hooks[currentHook++], setState]; | |
} | |
}; | |
})(); | |
function Counter() { | |
const [count, setCount] = MyReact.useState(0); | |
const [count1, setCount1] = MyReact.useState(0); | |
const ref = MyReact.useRef(10); | |
console.log(ref); | |
MyReact.useEffect(() => { | |
console.log("effect:", count); | |
console.log("effect1:", count1); | |
}, [count, count1]); | |
return { | |
click: () => setCount(count + 1), | |
render: () => console.log(`render: ${count} - render1: ${count1}`), | |
click1: () => setCount1(count1 + 1) | |
}; | |
} | |
let App; | |
App = MyReact.render(Counter); | |
App.click(); | |
App = MyReact.render(Counter); | |
App = MyReact.render(Counter); | |
App.click1(); | |
App = MyReact.render(Counter); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment