Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. import React, { useRef, useEffect } from "react";
  2.  
  3. const Timer = () => {
  4. const intervalRef = useRef();
  5.  
  6. useEffect(() => {
  7. const id = setInterval(() => {
  8. console.log("Um segundo se passou.");
  9. }, 1000);
  10.  
  11. /*
  12. Tornamos o id do intervalo acessível para todo o componente.
  13. Se tivéssemos usado uma variável de estado para isso,
  14. componente seria renderizado novamente e isso causaria um loop infinito.
  15. */
  16. intervalRef.current = id;
  17.  
  18. return () => clearInterval(intervalRef.current);
  19. });
  20.  
  21. const handleCancel = () => clearInterval(intervalRef.current);
  22.  
  23. return (
  24. <>
  25. //...
  26. </>
  27. );
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement