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

218
Visualizações
how do I set up a setTimeout without using a callback by the useEffect hook?

so as part of learning react I am currently converting a class-based App to a functional one, I've encountered some issues with my code since I can't use the callback function in the following context:

  class ColorBox extends Component {
  constructor(props) {
    super(props);
    this.state = { copied: false };
    this.changeCopyState = this.changeCopyState.bind(this);
  }
  changeCopyState() {
    this.setState({ copied: true }, () => {
      **setTimeout(() => this.setState({ copied: false }), 1500);**
    });
  }

I've tried to change it using the useEffect hook, to the following:

function ColorBox(props) {
const [isCopied, setIsCopied] = useState(false)

useEffect(() => setTimeout(() => setIsCopied(false), 1500), [isCopied])


const changeCopyState = () => {
    setIsCopied(true)
};

but the problem is that the useEffect renders at the first render which makes the app glitch if I don't wait for 1500ms before clicking on the copy button.

Any help would be greatly appreciated!!

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

0

the effects will fire whenever the values of their dependencies change. However, what you want according to your class-based approach is, after setting isCopied to true , to set it to false after 1500 ms.

To do this, check the current value of isCopied in your effect before you trigger the timeout.

 function ColorBox(props) { const [isCopied, setIsCopied] = useState(false) useEffect(() => { if (isCopied) { setTimeout(() => setIsCopied(false), 1500) } }, [isCopied, setIsCopied]) const changeCopyState = () => { setIsCopied(true) }; }

On top of that, for consistency, you may want to use clearTimeout when unmounting your effect (to avoid, for example, calling setIsCopied after the component has been unmounted).

To do so, the effect has to be like this.

 useEffect(() => { if (isCopied) { let timeoutId = setTimeout(() => setIsCopied(false), 1500) return () => clearTimeout(timeout) } }, [isCopied, setIsCopied])
about 4 years ago · Juan Pablo Isaza Relatório

0

When you don't specify braces {} in the arrow function, it will return a value.
In useEffect you don't need a value to be returned (the only exception is the componentWillUnmount lifecycle method). That led to unpredictable behavior and the wait time shot up on the initial render.
Use braces {} in your useEffect arrow function instead

 useEffect(() => { setTimeout(() => setIsCopied(false),1500) }, [isCopied]);
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