Created
December 5, 2021 01:33
-
-
Save webuniverseio/420bdaa1a84e1f05b98fe66e8f58b434 to your computer and use it in GitHub Desktop.
Hooks internals
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
// https://www.swyx.io/hooks/, https://www.youtube.com/watch?v=KJP1E-Y-xyo | |
const React = (function() { | |
let hooks = [] | |
let i = 0 | |
function useState(init) { | |
const state = hooks[i] || init | |
const currentIndex = i | |
const setState = newVal/*?*/ => hooks[currentIndex] = newVal | |
i++ | |
return [state, setState] | |
} | |
function render(Component) { | |
i = 0 | |
const C = Component() | |
C.render() | |
return C | |
} | |
function useEffect(cb, dependencies) { | |
const oldDependencies = hooks[i] | |
const hasChanged = !oldDependencies ? true : dependencies.some((x, idx) => !Object.is(x, oldDependencies[idx])) | |
if (hasChanged) { | |
cb() | |
} | |
hooks[i] = dependencies | |
} | |
return {useState, render, useEffect} | |
}()); | |
let result = React.render(Component) | |
result.click() | |
result = React.render(Component) | |
result.type('bla') | |
result = React.render(Component) | |
result.click() | |
result = React.render(Component) | |
function Component() { | |
const [{text, count}, setCount, setText] = useData() | |
return { | |
render: () => console.log({count, text}/*?*/), | |
click: () => setCount(count + 1), | |
type: word => setText(word) | |
} | |
} | |
function useData() { | |
const [count, setCount] = React.useState(1) | |
const [text, setText] = React.useState('apple') | |
React.useEffect(() => { | |
console.log('effect') | |
return () => { | |
} | |
}, [text]) | |
return [{count, text}, setCount, setText] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment