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

224
Visualizações
What is the best way to delay re-render for controlled components in React JS?

Let's say I have a simple controlled input component in React.

const ControlledInput = () => {

    const [state, setState] = React.useState("");

    const handleInputChange = (e) => {
        setState(e.target.value);
    };

    return <input type="text" value={state} onChange={handleInputChange} />
};

So, in this simple example, the component will be re-rendered with each character user entered. What is the best experience used to delay re-render? I mean user types to the input the word " I am user " and we want that re-render to happen when the user stops entering characters or maybe after 3 seconds when the user started to type?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I use SetTimeout to delay a re-render, here is code example

import React, { useState, useEffect } from 'react';

type Props = {
  children: React.ReactElement;
  waitBeforeShow?: number;
};

const Delayed = ({ children, waitBeforeShow = 500 }: Props) => {
  const [isShown, setIsShown] = useState(false);

  useEffect(() => {
    console.log(waitBeforeShow);
    setTimeout(() => {
      setIsShown(true);
    }, waitBeforeShow);
  }, [waitBeforeShow]);

  return isShown ? children : null;
};

export default Delayed;

And

export function LoadingScreen = ({ children }: Props) => {
  return (
    <Delayed>
      <div />
    </Delayed>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório

0

The best way, in this case, would be using the setTimeout() method for adding some delay to the rendering of component or API calls.

Note: In the below-shared example you should not use the inputValue var which I control using some delay it's sole purpose is to debounce the typing.

This is what you will have to use setTimeout() in a way that it gets cleared every time the user inputs something and for that, you will need to save setTimeout() reference using bellow snippet

var timoutId = setTimeout(cb,timeout);

After this, you can clear the timeout by calling this clearTimeout(timeoutId)

I have created a short demo which worth checking out: Sandbox demo

Here is the final snippet which is used in the above mentioned sandbox:

import React, { useState, useCallback } from "react";
import "./styles.css";

export default function App() {
  // for preserving input value with delay
  const [inputValue, setValue] = useState("");
  // to maintain the timeout ref
  let intervalId = React.useRef();
  // handle input change with delay
  const handleChange = useCallback((e) => {
    // input box value
    const value = e.target.value;
    console.log(value, "value");
    // clear the existing timout
    clearTimeout(intervalId.current);
    // reassign new timout ref
    intervalId.current = setTimeout(() => {
      setValue(value);
      console.log("I'm inside the setTimeout callback function!");
    }, 3000);
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <input onChange={handleChange} />
      <p>{inputValue}</p>
    </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