Skip to content

Instantly share code, notes, and snippets.

@indiesquidge
Created November 24, 2020 19:30
Show Gist options
  • Select an option

  • Save indiesquidge/579e56e547ce9828ca8dad60df13e900 to your computer and use it in GitHub Desktop.

Select an option

Save indiesquidge/579e56e547ce9828ca8dad60df13e900 to your computer and use it in GitHub Desktop.

Revisions

  1. indiesquidge created this gist Nov 24, 2020.
    24 changes: 24 additions & 0 deletions with-class.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    export class UserList extends React.Component {
    state = { count: 0 };

    handleClick = (item) => {
    setTimeout(() => {
    console.log(`You clicked ${this.props.group} ${this.state.count} times`);
    }, 3000);
    };

    render() {
    return (
    <div
    onClick={() => {
    this.setState({ count: this.state.count + 1 });
    }}
    >
    <HugeListOfItems
    group={this.props.group}
    handleClick={this.handleClick}
    />
    </div>
    );
    }
    }
    22 changes: 22 additions & 0 deletions with-hooks.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    export function UserList({ group }) {
    const [count, setCount] = React.useState(0);
    // Have to remember to useCallback here to avoid
    // the function getting recreated.
    const handleClick = React.useCallback(
    (item) => {
    setTimeout(() => {
    console.log(`You clicked ${group} ${count} times`);
    }, 3000);

    // Have to pass all of the variable references here so
    // React knows when to update the callback function.
    },
    [group, count]
    );

    return (
    <div onClick={() => setCount(count + 1)}>
    <HugeListOfItems group={group} handleClick={handleClick} />
    </div>
    );
    }