Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Network Requests Throttling in React Class Components

Supposing that I have a Search component that, when the user types something, would fire an API request to look for what is typed. When using React's useEffect Hook, it would be easy to throttle the API request's with a combination of setTimeout and clearTimeout (which is placed in the clean up function that useEffect returns). However, how can this be done in the Class component version of Search inside the componentDidUpdate lifecycle method?

function Search() {
  const [term, setTerm] = React.useState("");
  const [results, setResults] = React.useState([]);
  
  React.useEffect(() => {
    if(term)
      const timeOutId = window.setTimeout(() => {
        if (term)
          (async () => {
            const { data } = await axios.get(
              "https://en.wikipedia.org/w/api.php",
              {
                params: {
                  action: "query",
                  list: "search",
                  origin: "*",
                  format: "json",
                  srsearch: term,
                },
              }
            );

            setResults(data.query.search);
          })();
        }, 500);
      }

    return () => window.clearTimeout(timeoutId);
  }, [term]);

  return (
    /* some JSX */
  );
}
class Search extends React.Component {
  state = {
    term: '',
    results: []
  }

  componentDidUpdate(prevProps, prevState) {
    /* ??? */
  }

  render() {
    return (
      /* some JSX */
    );
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

While you could use componentDidUpdate() for this, it would be easier to handle most of the logic in the onChange handler of your input.

There are two important nuances to get right here. The first is that timeoutId should not be in state so it won't trigger any extra renders. The second part is to clean up the timeout after the component unmounts via componentWillUnmount(), so you won't leave any dangling calls to be made after your component no longer exists.

class Foo extends React.PureComponent {
  timeoutId = undefined;
  state = {
    term: ""
  };
  
  // Note that this method is bound so we can pass it directly to `onChange`
  onTermChange = (event) => {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    const term = event.target.value;
    this.setState({ term });
    this.timeoutId = setTimeout(() => {
      this.timeoutId = undefined;
      console.log(`timer fired with "${term}"`);
    }, 1000);
  };
  
  componentWillUnmount() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
  }

  render() {
    return (
      <input value={this.state.term} onChange={this.onTermChange} />
    );
  }
}

ReactDOM.render(<Foo />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!