-
-
Save b3nab/5a740deac36c3cbe0fd7730cf579aa21 to your computer and use it in GitHub Desktop.
Nested React Hooks
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
// Engine | |
const React = { | |
index: 0, | |
state: [], | |
useEffect: (callback, dependencies) => { | |
const cachedIndex = React.index; | |
const hasChanged = dependencies !== React.state[cachedIndex]; | |
if (dependencies === undefined || hasChanged) { | |
callback(); | |
React.state[cachedIndex] = dependencies; | |
} | |
if (React.state[cachedIndex] === undefined) { | |
React.state[cachedIndex] = dependencies; | |
} | |
React.index++; | |
return () => console.log('unsubscribed effect') | |
}, | |
useState: (defaultProp) => { | |
const cachedIndex = React.index; | |
if (!React.state[cachedIndex]) { | |
React.state[cachedIndex] = defaultProp; | |
} | |
const currentState = React.state[cachedIndex]; | |
const currentSetter = newValue => { | |
React.state[cachedIndex] = newValue | |
}; | |
React.index++; | |
return [currentState, currentSetter] | |
}, | |
render: (Component) => { | |
const exampleProps = { | |
unit: "likes" | |
}; | |
const compo = Component(exampleProps); | |
console.log("Render: ", compo.inner); | |
React.index = 0; | |
return compo; | |
} | |
} | |
const Component = props => { | |
[count, setCount] = React.useState(0); | |
[name, setName] = React.useState('Steve'); | |
const exitThis = React.useEffect(() => { | |
console.log('Effect ran') | |
}, name) | |
return { | |
type: "div", | |
inner: `${count} ${props.unit} for ${name}`, | |
click: () => setCount(count + 1), | |
personArrived: (person) => setName(person), | |
unsubscribe: () => exitThis() | |
} | |
} | |
// Exercise 1 | |
let App = React.render(Component) // Effect | |
App = React.render(Component) // No effect | |
App.click(); | |
App = React.render(Component) // No effect | |
App.click(); | |
App.personArrived("Peter"); | |
App = React.render(Component) // Effect | |
App.unsubscribe(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment