Thuta Learning
ရှာဖွေရန်
IntermediateWeb Developmentintermediate

Custom Hooks

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

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 ပြဿနာများဖြစ်နိုင်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Custom hook ကို condition ထဲမှာခေါ်မသုံးပါနဲ့။ Hooks တွေကို component/custom hook ရဲ့ top level မှာပဲခေါ်ပါ။
Custom Hooks | Thuta Learning