-
-
Save samsch/80a39fc0651b308dd6cf5fa9a12d9133 to your computer and use it in GitHub Desktop.
Comparing an Effect and State component to 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
import React from 'react'; | |
class Effect extends React.Component { | |
componentDidMount() { | |
this.previous = this.props.onRender(); | |
} | |
componentDidUpdate(prevProps) { | |
console.log('cdu'); | |
if ( | |
prevProps.cache && | |
this.props.cache && | |
prevProps.cache.length === this.props.cache.length && | |
prevProps.cache.every((prop, index) => { | |
return prop === this.props.cache[index]; | |
}) | |
) { | |
return; | |
} | |
this.clearPrevious(); | |
this.previous = this.props.onRender(); | |
} | |
componentWillUnmount() { | |
this.clearPrevious(); | |
} | |
clearPrevious() { | |
if (typeof this.previous === 'function') { | |
this.previous(); | |
} | |
} | |
render() { | |
return null; | |
} | |
} | |
class State extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
value: props.initial, | |
}; | |
this.childSetState = update => { | |
const updator = typeof update === 'function' ? update : () => update; | |
this.setState(state => ({ value: updator(state.value) })); | |
} | |
} | |
render() { | |
return (this.props.children || this.props.render)(this.state.value, this.childSetState); | |
} | |
} | |
const UsingComponents = () => { | |
return ( | |
<State initial={5} > | |
{(count, setCount) => ( | |
<span> | |
<Effect | |
onRender={() => { | |
const timeout = setTimeout(() => { | |
setCount(0); | |
}, 2000); | |
return () => { | |
clearTimeout(timeout); | |
} | |
}} | |
cache={[count > 10]} | |
/> | |
Count: {count} <button type="button" onClick={() => setCount(count => count + 1)}>Inc</button> | |
</span> | |
)} | |
</State> | |
); | |
}; | |
const UsingHooks = () => { | |
const [count, setCount] = React.useState(5); | |
React.useEffect(() => { | |
const timeout = setTimeout(() => { | |
setCount(0); | |
}, 2000); | |
return () => { | |
clearTimeout(timeout); | |
} | |
}, [count > 10]); | |
return ( | |
<span> | |
Count: {count} <button type="button" onClick={() => setCount(count => count + 1)}>Inc</button> | |
</span> | |
); | |
}; | |
export default () => ( | |
<> | |
<h4>Using Components</h4> | |
<UsingComponents /> | |
<h4>Using Hooks</h4> | |
<UsingHooks /> | |
</> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment