Skip to content

Instantly share code, notes, and snippets.

@interlark
Forked from simonw/react-debouncing.md
Created March 14, 2020 20:18
Show Gist options
  • Select an option

  • Save interlark/2463d8f5e5f20b284a2687f561f2a9e3 to your computer and use it in GitHub Desktop.

Select an option

Save interlark/2463d8f5e5f20b284a2687f561f2a9e3 to your computer and use it in GitHub Desktop.

Revisions

  1. Simon Willison created this gist Mar 16, 2018.
    56 changes: 56 additions & 0 deletions react-debouncing.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    # React debouncing pattern for API calls

    Classic debounce function:

    const debounce = (fn, delay) => {
    let timer = null;
    return function (...args) {
    const context = this;
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
    fn.apply(context, args);
    }, delay);
    };
    }

    A component that performs API calls on textinput change:

    class PlaceSearch extends Component {
    state = {
    q: '',
    places: [],
    }
    fetchPlaces(q) {
    get(`http://www.example.com/places/`, {
    params: {q}
    }).then(response => {
    this.setState({places: response.data.places});
    });
    }
    constructor(props) {
    super(props);
    this.fetchPlaces = debounce(this.fetchPlaces, 200);
    }
    onSearchChange(ev) {
    const q = ev.target.value;
    this.setState({q: q});
    this.fetchPlaces(q);
    }
    render() {
    return (
    <div>
    <input
    type="text"
    value={this.state.q}
    onChange={this.onSearchChange.bind(this)}
    placeholder="Search for a place"
    />
    {this.state.places.map(place => (
    <div key={place.id} className="placePick">
    <a href={`?place_id=${place.id}`}>{place.name}</a>
    </div>
    ))}
    </div>
    );
    }
    }