Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
State Management in React – Hooks, Context API and Redux
Next article icon

Mastering State Management in ReactJS: A Beginner's Guide to the Context API

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

State Management in React.js is an essential topic as the whole of React counters & controllers work through their states. State is the initial value of the component, or the current value & using state management we can change the value by some specific functionalities using react.js. One such important state management technique is through context API. In this article, we will learn how to master State Management in React.js & Context API.

Mastering-State-Management-in-React-copy

Below are the points thatwe will go through in this article:

Table of Content

  • State Management
  • What is Context API?
  • Setting up the Context API
  • Creating a Context Provider
  • Best Practices for using Context API
  • Advanced Usage of Context API
  • Performance Considerations
  • Migrating to Context API

State Management

React has an important usage termed as State Management. It involves managing the states of an entity by getting or setting its values by the use of useState hook from react dependency. For eg. A state name can be defined along with it's setter setName and an initial value of "" (An empty string). And if we apply any functionality to the file, then the name can be changed on the respective functionality.

Also, to manage the state we use context API. We can pass the states as props to further components for further usage and this takes place only from top to bottom. This is where context API plays a pivotal role in state management where states can be managed and transferred all across the directory.

What is Context API?

Context API is one of the most used react hooks that enable the transfer of props, or elements from one component to another. This is called the Passing of Props through different components. For eg. We want to pass the Name state from the Parent component to the Child component. This is called the passing of Props.

However, a major disadvantage of this Prop Drilling is that it can be too redundant at times & can increase the load on function calls. Plus, props can be passed from parent to child, but not vice-versa. Here's where Context API plays a pivotal role.

Context API is a react hook that is used in prop drilling. It allows passing of elements from parent to child, child to parent, and in fact, we can list the states in a universal context provider in our codebase, which will allow us to use the states in any component by simply importing it from the Provider.

Setting up the Context API

Step 1: Create a React application

npm create vite@latest
√ Project name: ... react-vite
√ Select a framework: » React
√ Select a variant: » JavaScript

Step 2: Install the dependencies.

npm i react-context

Updated Dependencies:

 "dependencies": {
"react": "^18.3.1",
"react-context": "^0.0.3",
"react-dom": "^18.3.1"
},

Project Structure:

projectStructure
Project structure

Creating a Context Provider

A Context Provider is a container type provider for the entire directory. It passes props or states and makes it available across the entire file tree. Using a context provider, we can specify the states & functions we want to use all over the file system and can further import it in the components respectively using context API hook. This helps us to keep a track of the states all over the file system and also import it from parents to children and children to parents components.

In Class Components

  • Class components is a bit more complicated to write cde than functional components. It requires creating a component that extends the Component from react and renders it it by calling a constructor when the file runs.
  • The App context provider is created and within which several states are passed as props and are used by this term which refers to the current state or props passed.
  • One can import the states using the Context Provider and use it anywhere across the directory.

Example: This example shows the creation of context provider using class component.

JavaScript
// App.jsx  import React, { createContext, Component } from "react";  const AppContext = createContext();  class AppContextProvider extends Component {   constructor(props) {     super(props);     this.state = {       user: { name: "ABC", email: "[email protected]" },     };   }    changeName = (userData) => {     this.setState({ user: userData });   };    render() {     return (       <AppContext.Provider         value={{ user: this.state.user, changeName: this.changeName }}       >         {this.props.children}       </AppContext.Provider>     );   } }  export { AppContext, AppContextProvider }; 
JavaScript
// Provider.jsx  import React, { Component } from "react"; import { AppContext } from "./App";  class App extends Component {     static contextType = AppContext;      handleChangeName = () => {         const { changeName } = this.context;         const data = { name: "RRJ", email: "[email protected]" };         changeName(data);     };      render() {         const { user } = this.context;          return (             <div style={{                 display: "flex",                 alignItems: "center",                 flexDirection: "column",                 marginTop: "180px"             }}>                 <div>                     <h2>User Profile</h2>                     <button onClick={this.handleChangeName}>Change Name to RRJ</button>                     {user && (                         <div>                             <h3>Welcome, {user.name}!</h3>                             <p>Email: {user.email}</p>                         </div>                     )}                 </div>             </div>         );     } }  export default App; 
JavaScript
// main.jsx  import React from "react"; import { createRoot } from "react-dom/client"; import App from "./provider"; import "./index.css"; import "./App.css";  import { AppContextProvider } from "./App";  createRoot(document.getElementById("root")).render(   <AppContextProvider>     <App />   </AppContextProvider> ); 

Output:

gif-context
Context Provider Class Component

In Functional Components

  • As the name suggests, we create a function in each component that returns the function on rendering of main.jsx file.
  • Here, we will use the createContext hook from react to create an AppContext.
  • We will now create a universal App context Provider that would consist of props. And according to the states and their initial values, we will create a function that will change the value of states.
  • Finally, wrap the props in an AppContextProvider and provide in value attribute, all functions or states.
  • Export the AppContext & AppContextProvider.

Example: This example shows the creation of context provider using functional component.

JavaScript
// App.jsx import React, { useContext } from "react"; import { AppContext } from "./Provider";  const App = () => {   const { user, changeName } = useContext(AppContext);    const data = { name: "RRJ", email: "[email protected]" };    return (     <div style={{ display: "flex", alignItems: "center", flexDirection: "column" }}>       <div>         <h2>User Profile</h2>         <button onClick={() => changeName(data)}>Change Name to RRJ</button>         {user && (           <div>             <h3>Welcome, {user.name}!</h3>             <p>Email: {user.email}</p>           </div>         )}       </div>     </div>   ); };  export default App; 
JavaScript
// Provider.jsx  import React, { createContext, useState } from "react";  const AppContext = createContext();  const AppContextProvider = ({ children }) => {     const [user, setUser] = useState({ name: "ABC", email: "[email protected]" });      const changeName = (userData) => {         setUser(userData);     };      return (         <AppContext.Provider value={{ user, changeName }}>             {children}         </AppContext.Provider>     ); };  export { AppContext, AppContextProvider }; 
JavaScript
// main.jsx  import React from "react"; import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./index.css"; import "./App.css";  import { AppContextProvider } from "./Provider";  createRoot(document.getElementById("root")).render(   <AppContextProvider>     <App />   </AppContextProvider> ); 

Output:

gif-context
Context Provider Functional Component

Best Practices for using Context API

  • Avoid Prop Drilling & use Context: Prop Drilling is when a state passes through so many parent classes that while reaching the end of Child class, it leads to endless re-renders & makes the application less efficient. There, use context API to use state at multiple places and anywhere within the directory.
  • Use Context only when necessary: Do not unnecessarily use context API, such as at places where prop needs to be passed only 1-2 times, adding context API will lead to a lot of re-renders and make the code slow. Use Context API only at the time of child to parent component states passing and where there is an excessive usage of props that further causes Prop Drilling.
  • Use Context Provider: The context provider ensures all props are wrapped up within and this allows usage of any state anywhere. Also, mention the props or functions in the value parameter in the provider jsx.

Advanced Usage of Context API

Context API is used in many large scale applications. One such advance usage of Context API is switching between light and dark themes in applications. We'll now create a setup that switches between light and dark theme states using context API.

  • Create a Context Provider with the name of DarkModeContext Provider that has a state of dark mode and a toggle function to toggle between the dark and light mode.
  • Pass these values through the Context Provider as children and use context hook in the App.jsx file to import the values of states & methods.
  • Apply respective class values on toggling of theme and change the style according to the theme.

Example: This example show the advance usage of Context API.

CSS
/* index.css */ * {   margin: 0;   padding: 0;   box-sizing: border-box;   font-family: 'Poppins', sans-serif; }  body {   transition: background-color 0.3s, color 0.3s; }  .light {   color: #000;   background-color: #fff; }  .dark {   color: #fff;   background-color: #000; }  h1 {   text-align: center;   margin: 20px 0; }  button {   display: block;   margin: 0 auto;   padding: 10px 20px;   border: none;   border-radius: 5px;   cursor: pointer;   font-size: 18px;   color: black;   font-weight: bolder; }  .light button {   background-color: #007bff;   color: #fff; }  .dark button {   background-color: #444;   color: #fff; }  button:hover {   opacity: 0.8; } 
JavaScript
// App.jsx  import React from "react"; import { useContext } from "react"; import { DarkModeContext } from "./DarkMode";  const App = () => {   const { darkTheme, toggleTheme } = useContext(DarkModeContext);    return (     <div>       <h1 className={darkTheme ? "dark" : "light"}>         I am currently in {darkTheme ? "Light Theme" : "Dark Theme"}       </h1>       <button onClick={toggleTheme}>Toggle Theme</button>     </div>   ); };  export default App; 
JavaScript
// DarkMode.jsx  import React, { useState } from "react"; import { createContext } from "react";  const DarkModeContext = createContext();  const DarkModeProvider = (props) => {     const [darkTheme, setDarkTheme] = useState(false);      const toggleTheme = () => {         setDarkTheme((darkTheme) => !darkTheme);     };      const value = { darkTheme, toggleTheme };      return (         <DarkModeContext.Provider value={value}>             {props.children}         </DarkModeContext.Provider>     ); };  export { DarkModeProvider, DarkModeContext }; 
JavaScript
// main.jsx  import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./index.css"; import { DarkModeProvider } from "./DarkMode.jsx";  createRoot(document.getElementById("root")).render(   <DarkModeProvider>     <App />   </DarkModeProvider> ); 

Output:

Toggletheme
Toggle Theme using Context API

Performance Considerations

  • React Context API has a great performance and stability when it comes to small to mediocre scale applications. The props which could not be passed from child component to parent component can be easily achieved through context API. This makes usage of prop handling lesser and reduces the inefficiency created due to prop drilling.
  • React Context API is better than Redux as it involves beginner friendly code and the performance is also great for small scale applications. Redux involves a bit of complicated code that developers take time to understand as compared to react context which is easy to implement.
  • However, there arises a performance consideration in react context API which makes usage of Redux even better still today. For every state you call with the Context API, those states which do not change also get re-rendered along with those states which are called. This is a huge negative aspect of Context API as it may lead to crashing of application as those states which are not supposed to render end up getting so.

Migrating to Context API

  • Beginners should use Context API since it provides them a better learning and immersive experience for using states across directory.
  • Redux mostly involves a lot of heavy codes and abstractions including the reducer & dispatch boiler plate code functions that make the beginners very difficult to understand. This is where Context API helps. Once when you learn context API, migrating to Redux or Mobx is easier.
  • Use Context API as it helps in removing the inefficiency of prop drilling. Also, to remove the problem of re-rendering of every state in the file, one can use the solution of multiple contexting. Here, those states which render won't affect the other states with a different context provider since there can be more than one providers.

Conclusion

React Context API is a mediocre level difficulty topic to understand. However, it is a very important aspect of Development, since large websites use context API to transfer user data obtained during authentication. It also is useful when problems such as Prop Drilling arise when a state is passed from a parent class to multiple sub classes & this causes extensive re-renders. React, being an open source language has amazing documentation & resources on React Context API that users can refer to and read.


Next Article
State Management in React – Hooks, Context API and Redux
author
riyarjha
Improve
Article Tags :
  • GBlog
  • Web Technologies
  • ReactJS
  • Web-Tech Blogs

Similar Reads

  • Using the React Context API for Efficient State Management
    The React Context API is a robust feature announced in React 16.3. It offers a way to share data within components without passing props directly at all stages. This is specifically useful for global data that many components seek to access, like user authentication, theme, or language settings. Rat
    5 min read
  • State Management in React – Hooks, Context API and Redux
    State management is a critical concept when working with React. React components can hold local state, but as applications grow, managing state across multiple components can become complex. To help manage this complexity, React provides several tools: Hooks, Context API, and Redux. Here are some fe
    6 min read
  • State Management in React: Context API vs. Redux vs. Recoil
    A fundamental idea in application development, State management is especially important for contemporary online and mobile apps, where dynamic, interactive user experiences necessitate frequent modifications to data and interface components. Fundamentally, it describes how an application maintains a
    12 min read
  • Getting Started With ReactJS: A Complete Guide For Beginners
    Every front-end developer and web developer knows how frustrating and painful it is to write the same code at multiple places. If they need to add a button on multiple pages they are forced to do a lot of code. Developers using other frameworks face the challenges to rework most codes even when craf
    7 min read
  • Introduction to Recoil For State Management in React
    State Management is a core aspect of React development, especially as applications grow in size and complexity. While there are many libraries available to handle state, recoil has emerged as the fresh, modern approach that simplifies state management without the bloat of more complex systems like R
    7 min read
  • Simplifying State Management with Redux in MERN Applications
    In this project, we've developed a todo web application utilizing the MERN stack (MongoDB, Express.js, React.js, Node.js) with Redux for state management. In this project, a todo can be created, viewed, and also saved in the database. Output Preview: Let us have a look at how the final output will l
    6 min read
  • How to manage global state in a React application?
    Global state refers to data that is accessible across multiple components in a React application. Unlike the local state, which is confined to a single component, the global state can be accessed and modified from anywhere in the component tree. In this article, we will explore the following approac
    7 min read
  • How to locally manage component's state in ReactJS ?
    Any component in React JS majorly depends on its props and state to manage data. A component's state is private to it and is responsible for governing its behavior throughout its life. A state is nothing but a structure that records any data changes in a react application. It can be used for storing
    2 min read
  • Handling State and State Management | System Design
    State management is a critical aspect of system design that involves managing the state or condition of a system at any given point in time. In software development, state refers to the current values of variables, data, and configurations that determine the behavior of an application or system. Eff
    12 min read
  • Document Management System with React and Express.js
    This project is a Document Management System (DMS) developed with a combination of NodeJS, ExpressJS for the server side and React for the client side. The system allows users to view, add, and filter documents. The server provides a basic API to retrieve document data, while the React application o
    6 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