Custom Hook ဆိုတာ reusable logic ကို `use...` နာမည်နဲ့ function အဖြစ်ခွဲထုတ်ထားတာပါ။ Component များစွာမှာတူညီတဲ့ state/effect logic သုံးရတဲ့အခါ copy-paste မလုပ်ဘဲ hook တစ်ခုရေးပြီးပြန်သုံးနိုင်ပါတယ်။
jsx
import { useEffect, useState } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
function App() {
const width = useWindowWidth();
return <p>Window width is {width}px</p>;
}`useWindowWidth` hook က browser width ကို state ထဲသိမ်းပြီး resize ဖြစ်တိုင်း update လုပ်ပါတယ်။ Component က hook ကိုခေါ်သုံးပြီး width ကို UI ထဲပြပါတယ်။
You should see
Browser window အကျယ်ကို pixel နဲ့ပြပြီး window size ပြောင်းတိုင်း update ဖြစ်မယ်။Info
Event listener ထောင်ထားတာကြောင့် cleanup function နဲ့ ပြန်ဖြုတ်ထားပါတယ်။ ဒါမလုပ်ရင် memory leak သို့မဟုတ် duplicated listener ပြဿနာများဖြစ်နိုင်ပါတယ်။