Skip to content

Instantly share code, notes, and snippets.

@MinthangML
Created December 21, 2020 04:56
Show Gist options
  • Save MinthangML/9281bcf32899fee544a741fd2601c31d to your computer and use it in GitHub Desktop.
Save MinthangML/9281bcf32899fee544a741fd2601c31d to your computer and use it in GitHub Desktop.
Store a mutable variable in Ref
import React, { useRef, useEffect } from "react";
const Timer = () => {
const intervalRef = useRef();
useEffect(() => {
const id = setInterval(() => {
console.log("A second has passed");
}, 1000);
// component တစ်ခုလုံးကနေ ယူသုံး (accessible) နိုင်ဖို့အတွက် interval id လိုအပ်ပါတယ်
// id ကို state variable ထဲမှာ သိမ်းထားမယ်ဆိုရင် component က re-render ပါလိမ့်မည်။
//state ကို update လုပ်တိုင်း interval အသစ်တစ်ခုကို create လုပ်မှာဖြစ်တဲ့အတွက် (re-render လုပ်တိုင်းလည်း ဒီလိုမျိုးဖြစ်) infinite loop hell ဖြစ်စေပါလိမ့်မည်။
intervalRef.current = id;
return () => clearInterval(intervalRef.current);
});
const handleCancel = () => clearInterval(intervalRef.current);
return (
<>
//…
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment