Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda