ReactJS useContext Hook Last Updated : 23 Jul, 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.Syntaxconst 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 ContextBefore 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 Hook1. Managing Authentication with useContextuseContext 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; OutputReactJS useContext HookIn this exampleAuthContext 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 ComponentsWe 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; OutputReactJS useContext HookIn this exampleThemeContext 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 useContextWe can use the useContext whenWe 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 DrillingFeatureuseContextProp DrillingPerformanceGood (Can cause unnecessary renders)EfficientBest forSmall to medium appsFew component levelsUse CaseGlobal state sharingPassing props manuallyPerformance ConsiderationsTo 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. ReactJS useContext Hook Visit Course Comment More infoAdvertise with us R rbbansal Follow Improve Article Tags : Web Technologies ReactJS React-Hooks Similar Reads React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version 7 min read React FundamentalsReact IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() { 6 min read React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be 3 min read React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al 2 min read React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi 5 min read ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements 3 min read React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a 4 min read React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name, 4 min read ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th 4 min read Components in ReactReact ComponentsIn React, components are reusable, independent code blocks (A function or a class) that define the structure and behavior of the UI. They accept inputs (props or properties) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its 4 min read ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Example:JavaScriptimport 4 min read React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el 3 min read ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p 4 min read ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon 2 min read ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he 5 min read React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo 7 min read React HooksReact HooksReactJS Hooks, introduced in React 16.8, are among the most impactful updates to the library, with over 80% of modern React projects adopting them for state and lifecycle management. They let developers use state, side effects, and other React features without writing class components. Hooks streaml 8 min read React useState HookThe 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 ReactJS useEffect HookThe 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.Fetchin 5 min read Routing in ReactReact RouterReact Router is a JavaScript library designed specifically for React to handle client-side routing. It maps specific URL paths to React components, allowing users to navigate between different pages or sections without refreshing the entire page.Types of React RoutersThere are three types of routers 5 min read React JS Types of RoutersWhen creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour.What is React Router?React Router is a declarati 10 min read Advanced React ConceptsLazy Loading in React and How to Implement it ?Lazy Loading in React is used to initially load and render limited data on the webpage. It helps to optimize the performance of React applications. The data is only rendered when visited or scrolled it can be images, scripts, etc. Lazy loading helps to load the web page quickly and presents the limi 4 min read ReactJS Higher-Order ComponentsHigher-order components (HOC) are an advanced technique in React that is used for reusing component logic. It is the function that takes the original component and returns the new enhanced component.It doesnât modify the input component directly. Instead, they return a new component with enhanced be 5 min read Code Splitting in ReactCode-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties 4 min read React ProjectsCreate ToDo App using ReactJSThis to-do list allows users to add new tasks and delete them by clicking the corresponding button. The logic is handled by a click event handler whenever the user clicks on a task it gets deleted from the list.Lets have a quick look at what the final application will look like:ToDo App using ReactJ 3 min read Create a Quiz App using ReactJSIn this article, we will create a quiz application to learn the basics of ReactJS. We will be using class components to create the application with custom and bootstrap styling. The application will start with questions at first and then the score will be displayed at last. Initially, there are only 4 min read Create a Coin Flipping App using ReactJSIn this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind 3 min read How to create a Color-Box App using ReactJS?Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its prev 4 min read Dice Rolling App using ReactJSThis article will create a dice-rolling application that rolls two dice and displays a random number between 1 and 6 as we click the button both dice shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers on the upper face are genera 4 min read Guess the number with ReactIn this article, we will create the guess the number game. In which the computer will select a random number between 1 and 20 and the player will get unlimited chances to guess the number. If the player makes an incorrect guess, the player will be notified whether the guess is is higher or lower tha 3 min read Like