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

useContext Hook

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

`useContext` သည် parent မှ child ထဲကို props များအဆင့်ဆင့်လက်ဆင့်ကမ်းစရာမလိုဘဲ data ကို component tree အတွင်း share လုပ်နိုင်တဲ့နည်းလမ်းပါ။ Theme, language, logged-in user, app settings စတာတွေကို child component များစွာမှာလိုအပ်တဲ့အခါ အသုံးဝင်ပါတယ်။

jsx
import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemeLabel() {
  const theme = useContext(ThemeContext);
  return <p>Current theme: {theme}</p>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemeLabel />
    </ThemeContext.Provider>
  );
}

`ThemeContext.Provider` က `dark` ဆိုတဲ့ value ကိုအောက်က component tree ဆီပေးပါတယ်။ `ThemeLabel` က `useContext(ThemeContext)` နဲ့ value ကိုယူပြီး UI ထဲပြပါတယ်။

You should see
Browser မှာ `Current theme: dark` ဆိုတဲ့စာသား ပေါ်လာမယ်။

Info

Props drilling ကြီးလာတဲ့အခါ Context သုံးရင် code ရှင်းသွားနိုင်ပေမယ့် data ပြောင်းလဲမှုများတဲ့ state တွေကို context ထဲပစ်ထည့်တာက performance ကိုထိနိုင်ပါတယ်။

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

  • Provider မပါဘဲ `useContext` သုံးရင် `createContext()` ထဲပေးထားတဲ့ default value ကိုသာရနိုင်ပါတယ်။
useContext Hook | Thuta Learning