DEV Community

Madhan Raj
Madhan Raj

Posted on

ReactJS useContext Hook

ReactJS useContext Hook

The useContext hook in React allows components to consume values from the React context. React’s context API is primarily designed to pass data down the component tree without manually passing props at every level. useContext is a part of React's hooks system, that enables functional components to access context values.

1.Simplifies accessing shared state across components.
2.Avoids prop drilling by eliminating the need to pass props down multiple levels.
3.Works seamlessly with React's Context API to provide global state.
4.Ideal for managing themes, authentication, or user preferences across the app.

Syntax:

const contextValue = useContext(MyContext);

MyContext: The context object is created using React.createContext().
contextValue: The current context value that we can use in our component.
Enter fullscreen mode Exit fullscreen mode

Working of useContext

The useContext hook allows to consume values from a React Context, enabling easy access to shared state across multiple components without prop drilling. Here’s how it works:

useContext hook consumes values from a React Context, making them accessible to functional components.
First, create a Context object using React.createContext(), which holds the shared state.
Use useContext to access the context value in any component that needs it, avoiding prop drilling.
When the value of the Context updates, all components consuming that context automatically re-render with the new value.
Enter fullscreen mode Exit fullscreen mode

1. Managing Authentication with useContext

useContext can be used for managing the user authentication state globally

import React, { createContext, useContext, useState } from 'react';
const AuthContext = createContext();
function AuthProvider({ children }) {
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    return (
        <AuthContext.Provider value={{ isLoggedIn, setIsLoggedIn }}>
            {children}
        </AuthContext.Provider>
    );
}
function LoginButton() {
    const { isLoggedIn, setIsLoggedIn } = useContext(AuthContext);
    return (
        <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
            {isLoggedIn ? 'Logout' : 'Login'}
        </button>
    );
}
function App() {
    return (
        <AuthProvider>
            <LoginButton />
        </AuthProvider>
    );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

In this code,

AuthContext is created using createContext() and AuthProvider manages the isLoggedIn state, passing it down through the context.
LoginButton uses useContext to access isLoggedIn and setIsLoggedIn from the context and toggles the login state.
App renders LoginButton wrapped in AuthProvider, allowing dynamic login/logout functionality.
Enter fullscreen mode Exit fullscreen mode

Output

Performance Considerations

Minimize Re-renders: Avoid unnecessary re-renders by memoizing values and functions using useMemo and useCallback.
Efficient State Initialization: Use lazy initialization in useState for expensive computations.
Cleanup Effects: Always clean up side effects in useEffect to prevent memory leaks.
Limit Dependencies: Keep dependencies in useEffect minimal to reduce unnecessary executions.
Enter fullscreen mode Exit fullscreen mode

Reference
https://www.geeksforgeeks.org/reactjs/reactjs-usecontext-hook/

Top comments (1)

Collapse
 
vidhya_murali_5aabe7784bd profile image
vidhya murali

nice