Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
ReactJS useContext Hook
Next article icon

ReactJS useContext Hook

Last Updated : 05 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In React Applications, sometimes managing state across deeply nested components can become very difficult. The useContext hook offers a simple and efficient solution to share state between components without the need for prop drilling.

What is 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, introduced in React 16.8, that enables functional components to access context values.

It helps avoid the problem of "prop drilling," where props are passed down multiple levels from parent to child components.

  • Simplifies accessing shared state across components.
  • Avoids prop drilling by eliminating the need to pass props down multiple levels.
  • Works seamlessly with React's Context API to provide global state.
  • 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.

How does it work?

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.

Creating a Context

Before using useContext, we need to create a context using React.createContext(). This context will provide a value that can be accessed by any child component wrapped in a Context.Provider.

JavaScript
import React, { createContext, useContext, useState } from 'react';  const MyContext = createContext();  function App() {     const [value, setValue] = useState('Hello, World!');      return (         <MyContext.Provider value={value}>             <ChildComponent />         </MyContext.Provider>     ); }  function ChildComponent() {     const contextValue = useContext(MyContext);     return <h1>{contextValue}</h1>; } 
  • createContext() creates a context object (MyContext) that holds a default value.
  • MyContext.Provider passes down the context value to its child components.
  • useContext(MyContext) allows components like ChildComponent to access the context value.

Implementing the useContext Hook

1. Managing Authentication with useContext

useContext can be used for managing the user authentication state globally.

JavaScript
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; 

Output

Animationkk
ReactJS useContext Hook

In this example

  • 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.

2. Sharing a Theme Across Components

We will create a theme context and use useContext to access its values in child components.

JavaScript
import React, { createContext, useContext, useState } from 'react';  const ThemeContext = createContext(); function ThemeProvider({ children }) {     const [theme, setTheme] = useState('light');      const toggleTheme = () => {         setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));     };      return (         <ThemeContext.Provider value={{ theme, toggleTheme }}>             {children}         </ThemeContext.Provider>     ); } function ThemedComponent() {     const { theme, toggleTheme } = useContext(ThemeContext);     return (         <div style={{ background: theme === 'light' ? '#fff' : '#333',              color: theme === 'light' ? '#000' : '#fff', padding: '20px', textAlign: 'center' }}>             <p>Current Theme: {theme}</p>             <button onClick={toggleTheme}>Toggle Theme</button>         </div>     ); } function App() {     return (         <ThemeProvider>             <ThemedComponent />         </ThemeProvider>     ); }  export default App; 

Output

Animationkk
ReactJS useContext Hook

In this example

  • ThemeContext is created using createContext().
  • ThemeProvider manages the theme state and provides a toggleTheme function.
  • useContext(ThemeContext) in ThemedComponent allows access to the current theme and the ability to toggle it.
  • Clicking the button switches between light and dark themes.

When to Use useContext

We can use the useContext when

  • We need global state management for themes, authentication, or user preferences.
  • We want to avoid prop drilling.
  • We need state sharing between multiple components without a third-party state management library.

useContext vs Prop Drilling

Feature

useContext

Prop Drilling

Performance

Good (Can cause unnecessary renders)

Efficient

Best for

Small to medium apps

Few component levels

Use Case

Global state sharing

Passing props manually

Performance Considerations

To optimize performance when using React hooks:

  • 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.

Next Article
ReactJS useContext Hook

R

rbbansal
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

    ReactJS useEffect Hook
    The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is
    4 min read
    ReactJS useLayoutEffect Hook
    The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
    2 min read
    React useState Hook
    The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
    5 min read
    Purpose of the useContext hook
    The useContext hook in React makes it easier for components to get data from the overall theme or settings of your app. In React, "context" is like a way to share information among different parts of your app without having to hand it down through each piece. So, useContext helps a component quickly
    2 min read
    React useInsertionEffect Hook
    React useInsertionEffect Hook is used in React 18 to insert elements like dynamic styles, into the DOM before the layout effects are fired. This hook is mainly created to run on the client side, which makes it perfect for situations where the pre-layout element insertion is important. Syntax:useInse
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences