Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 />
- </>
- );
Add Comment
Please, Sign In to add comment