
Usecontext in ReactJS
✅ useContext in ReactJS
useContext
is a React Hook that allows you to access global state without passing props manually at every level. It is often used for managing theme, authentication, or language across a React application.
📌 Why Use useContext
?
Avoid Prop Drilling → No need to pass data through multiple components.
Centralized State Management → Share state between components easily.
Cleaner Code → Reduces redundancy and makes code more readable.
📌 Syntax
jsx<ThemeContext.Provider <div <ThemeProvider> <AuthContext.Provider <div <AuthProvider> <ThemeProvider> <Profile /> </ThemeProvider> </AuthProvider>);export default App;
🛠 Explanation:
Multiple Contexts → Both
AuthContext
andThemeContext
are used.Flexible Management → You can manage both auth state and theme state independently.
📌 3. When to Use useContext
?
✅ Use useContext
when:
You need to avoid prop drilling.
State or functions need to be accessed globally.
Components like theme switchers or user authentication need access to shared data.
❗ Avoid useContext
when:
The data is only needed in one or two components.
It is more suitable to pass props instead.
You require advanced state management — use libraries like Redux or Zustand instead.
📌 4. Conclusion
useContext
is an efficient way to share state without prop drilling.It simplifies state management for global features like themes and authentication.
Combine it with
useState
,useEffect
, oruseReducer
for complex state logic.f combininguseMemo
withuseCallback
? 😊