Waa maxay Context API?
Context API waa hab ay React u adeegsaneyso in xog la wadaago inta u dhexeysa qaybaha kala duwan ee codsiga adigoo aan u baahneyn inaad si toos ah u marsiiso props. Waxay kuu ogolaaneysaa inaad abuurto "context" halkaas oo xogta lagu kaydinayo, kadibna qaybaha u baahan xogtaas si toos ah ay uga helayaan.
![]() |
Simplifying global state management in React without props drilling using Context API |
waa inaan sidhow diirada usaaartaa context API maxaa yeelay waxa uu muhiim uyahay react js marka laga hadlaayo web application aad ayay muhiim utahay in laisticmaalo api haddii kale waxa ay noqonkartaa culeyst inaan dhisto application dhameystiran marka waxaay kuu fududeyneysaa inaad si smoothly ah u hesho xogta,
Sida Context API u Shaqeeyo
Si aad u isticmaasho Context API, waxaa jira saddex qaybood oo muhiim ah:
- Context Creation - Abuurista Context.
- Provider - Qaybta bixisa xogta.
- Consumer - Qaybaha isticmaala xogta.
1. Abuurista Context
Marka hore, waa in la abuuro Context adigoo adeegsanaya createContext
:
import { createContext } from "react";
const ThemeContext = createContext();
export default ThemeContext;
2. Bixinta Xogta (Provider)
Qaybta bixisa xogta waa Provider, taasoo u ogolaaneysa dhammaan qaybaha hoose inay helaan xogta:
import { useState } from "react";
import ThemeContext from "./ThemeContext";
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
export default ThemeProvider;
3. Isticmaalka Xogta (Consumer)
Qaybaha u baahan xogta waxay isticmaali karaan useContext
si ay si fudud u helaan:
import { useContext } from "react";
import ThemeContext from "./ThemeContext";
const ThemeSwitcher = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<p>Theme: {theme}</p>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Bedel Theme
</button>
</div>
);
};
export default ThemeSwitcher;
![]() |
Simplifying global state management in React without props drilling using Context API |
Faa'iidooyinka Context API
- Yareynta Props Drilling – Ma jiro baahi aad props u marsiiso qayb kasta.
- Maareyn fudud – Waa sahlan tahay in la maareeyo state global ah.
- Hagaajinta Waxqabadka – Qaybaha aan u baahneyn xogta lama cusbooneysiinayo mar kasta oo state is bedesho.
Gabagabadii iyo gunaanidkii ayaanu soo gaarney saaxiibayaal
Context API waa hab fudud oo wax ku ool ah oo lagu maareeyo state global ah adigoo ka fogaanaya dhibaatada props drilling. Waxaa habboon in aad adeegsato marka xogta ay u baahan tahay in laga wada helo qaybo badan oo ka mid ah codsiga React. Haddii aad u baahato maareyn xog aad u ballaaran, waxaa sidoo kale jira xalal kale sida Redux ama Zustand.
Hadda oo aad fahamtay Context API, isku day inaad ku isticmaasho mashruucaaga React si aad si fiican u fahanto sida uu u shaqeeyo!