Custom Hooks နဲ့ Behavior ပြန်သုံးခြင်း

19.3

Custom Hook က ပြန်သုံးလိုတဲ့ stateful logic ကို စုပါတယ်။ Shared source တစ်ခုကနေ မဖတ်ရင် ခေါ်တဲ့ component တစ်ခုစီမှာ ကိုယ်ပိုင် state ရပါတယ်။

ဒီစာမျက်နှာမှာ

External Subscription ကို Hook ထဲ ထည့်ခြင်း

External value နဲ့ change events ရှိတဲ့ browser API အတွက် useSyncExternalStore နဲ့ subscribe လုပ်ပြီး snapshot ဖတ်နိုင်ပါတယ်။ ဒီ client-only ဥပမာက online flag ဖတ်ပါတယ်။ Server မှာ render လုပ်ရင် server snapshot ပါ ပေးပါ။

import { useSyncExternalStore } from "react";

function subscribe(notify) {
  window.addEventListener("online", notify);
  window.addEventListener("offline", notify);
  return () => {
    window.removeEventListener("online", notify);
    window.removeEventListener("offline", notify);
  };
}

export function useOnlineStatus() {
  return useSyncExternalStore(subscribe, () => navigator.onLine);
}

Rules of Hooks လိုက်နာခြင်း

Custom Hook နာမည်ကို use နဲ့ စပြီး နောက်မှာ စာလုံးအကြီး လိုက်ပါ။ Hooks တွေကို component သို့ custom Hook ရဲ့ top level မှာ ခေါ်ပါ။ Hook မခေါ်တဲ့ function က ပုံမှန် function အဖြစ် ထားနိုင်ပါတယ်။

import { useState } from "react";

function useSearchQuery() {
  const [query, setQuery] = useState("");
  return { query, setQuery };
}

export default function SearchPanel({ visible = true }) {
  const { query, setQuery } = useSearchQuery();
  if (!visible) return null;

  return (
    <label>
      Search
      <input value={query} onChange={event => setQuery(event.target.value)} />
    </label>
  );
}

တရားဝင် ကိုးကားချက်များ