React JS useContext Hook
The useContext
hook is a fundamental hook in React that allows functional components to access the context values provided by a Context
object. Context provides a way to share values like themes, authentication status, or user data across the component tree without passing props manually through every level.
Key Concepts of useContext
Creating Context:
- First, you need to create a context object using
React.createContext()
. This object includes a Provider component to provide the context value and a Consumer component to consume the context value. WithuseContext
, you can directly access the context value in functional components. - Example:
import React, { createContext, useState } from 'react'; const ThemeContext = createContext(); // Create Context function App() { const [theme, setTheme] = useState('light'); return ( <ThemeContext.Provider value={theme}> <ThemedComponent /> </ThemeContext.Provider> ); } function ThemedComponent() { const theme = useContext(ThemeContext); // Access Context Value return <div>The current theme is {theme}</div>; } export default App;
- First, you need to create a context object using
Using
useContext
:- The
useContext
hook takes a context object (the one created withReact.createContext()
) as its argument and returns the current context value. This value is provided by the nearestContext.Provider
up the tree. - Syntax:
const value = useContext(Context);
- Example:
import React, { createContext, useContext, useState } from 'react'; const LanguageContext = createContext('en'); // Default value is 'en' function LanguageProvider({ children }) { const [language, setLanguage] = useState('en'); return ( <LanguageContext.Provider value={language}> {children} </LanguageContext.Provider> ); } function LanguageDisplay() { const language = useContext(LanguageContext); // Access Context Value return <div>Current language: {language}</div>; } function App() { return ( <LanguageProvider> <LanguageDisplay /> </LanguageProvider> ); } export default App;
- The
Default Values:
- When creating a context with
React.createContext()
, you can provide a default value. This default value is used when a component consuming the context is not within aContext.Provider
that provides a value. - Example:
const AuthContext = createContext({ isAuthenticated: false });
- When creating a context with
Context Value Updates:
- When the context value provided by a
Context.Provider
changes, all components consuming that context will re-render with the new value. - Example:
import React, { createContext, useContext, useState } from 'react'; const UserContext = createContext(); function UserProvider({ children }) { const [user, setUser] = useState(null); const login = (userData) => setUser(userData); const logout = () => setUser(null); return ( <UserContext.Provider value={{ user, login, logout }}> {children} </UserContext.Provider> ); } function UserProfile() { const { user, logout } = useContext(UserContext); return ( <div> {user ? ( <> <p>Welcome, {user.name}</p> <button onClick={logout}>Logout</button> </> ) : ( <p>Please log in.</p> )} </div> ); } function App() { return ( <UserProvider> <UserProfile /> </UserProvider> ); } export default App;
- When the context value provided by a
Nested Contexts:
- You can use multiple contexts in a component and nest
Context.Provider
components to provide different values to different parts of the component tree. - Example:
import React, { createContext, useContext, useState } from 'react'; const ThemeContext = createContext('light'); const AuthContext = createContext(false); function App() { const [theme, setTheme] = useState('light'); const [isAuthenticated, setIsAuthenticated] = useState(false); return ( <ThemeContext.Provider value={theme}> <AuthContext.Provider value={isAuthenticated}> <Component /> </AuthContext.Provider> </ThemeContext.Provider> ); } function Component() { const theme = useContext(ThemeContext); const isAuthenticated = useContext(AuthContext); return ( <div> <p>Theme: {theme}</p> <p>Authenticated: {isAuthenticated ? 'Yes' : 'No'}</p> </div> ); } export default App;
- You can use multiple contexts in a component and nest
Summary
- Creating Context: Use
React.createContext()
to create a context object. This object includes a Provider to supply context values and a Consumer to access context values. - Using
useContext
: TheuseContext
hook accesses the context value directly in functional components, eliminating the need for theContext.Consumer
component. - Default Values: Default values are used when a component is not within a
Context.Provider
. - Context Value Updates: When the context value changes, all components consuming that context are re-rendered with the new value.
- Nested Contexts: Multiple contexts can be used in a component, and they can be nested to provide different values to different parts of the component tree.
The useContext
hook simplifies accessing context values in functional components, making it easier to manage and share state across the component tree without passing props manually.