Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda