Skip to content

Instantly share code, notes, and snippets.

@webuniverseio
Created December 5, 2021 01:33
Show Gist options
  • Save webuniverseio/420bdaa1a84e1f05b98fe66e8f58b434 to your computer and use it in GitHub Desktop.
Save webuniverseio/420bdaa1a84e1f05b98fe66e8f58b434 to your computer and use it in GitHub Desktop.
Hooks internals
// 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