Skip to content

Instantly share code, notes, and snippets.

@samsch
Created December 15, 2018 19:05
Show Gist options
  • Save samsch/80a39fc0651b308dd6cf5fa9a12d9133 to your computer and use it in GitHub Desktop.
Save samsch/80a39fc0651b308dd6cf5fa9a12d9133 to your computer and use it in GitHub Desktop.
Comparing an Effect and State component to Hooks
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