This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Simplifying State with Context API

  • ReactJS
  • July 19, 2024

Share On :

Introduction:

Renowned for its efficiency and flexibility, the React framework provides numerous features that enable developers to build robust and scalable web applications. One standout feature is the React Context API, which allows developers to manage state and share data across the component tree without relying on prop drilling. The Context API is particularly valuable for handling “global” data needed by multiple components, such as user authentication and theme settings.

Prerequisites:
  • Node.js and npm
  • React
  • Typescript
  • React Hooks
Understanding Advance Usage of Context API: 

The following sections will offer a deeper dive into the Context API. Whether you’re new to React or looking to enhance your knowledge of state management, this blog will give useful insights and guidance.

  • Understanding the Basics of React Context:

Introduced in React 16.3, React Context is a feature that enables data sharing between components without the need to pass it through props. The Context API addresses the issue of “prop drilling,” where data must be passed down from top-level components to lower levels in the component tree. By using the Context API, you can share data globally across the entire component tree, simplifying the process.

  • When & When not to use the Context API:

It is useful when data needs to be shared across multiple components that are not directly related to each other.

React Context has its drawbacks, and overusing it can lead to performance problems. When the context value updates, it can trigger unnecessary re-renders in consuming components, even if the updates are irrelevant to them. This can negatively affect performance, especially in larger component trees.

For frequently updated states, React Context might not be as efficient as tools like React Redux. However, for static data that updates infrequently, such as preferred language, time changes, location changes, and user authentication, React Context is a suitable choice for passing down props.

  • Context API vs Redux:

Choosing between React Context API and Redux depends on the specific requirements and complexity of your application.

Use React Context API:

    • Small to medium-sized applications
    • Fewer levels of data sharing
    • Component-specific state

Use Redux:

    • Large and complex applications
    • Deeply nested components
    • Asynchronous data flow
  • Use Cases of Context API:

Following are some real-world use cases of Context API

    • Multi-Language Support: You can store the current language of your application in the context and pass it down to all the components that require it. This way, you can easily switch between different languages without having to pass the language down as props to all the components.
    • User Authentication: You can use Context API to store a user’s authentication status and pass it down to all the components that require it. This way, you can easily restrict access to certain parts of your application based on the user’s authentication status.
    • Theming: Utilizing the Context API enables you to store the current theme of your application and share it with all components. Consequently, whenever the user changes the theme, all components will automatically reflect the new theme.
    • Accessing data from external sources: The Context API can be used to store data fetched from external sources, such as APIs or databases, and make it accessible to all components. This approach can simplify your code and streamline data handling across your application.
A Comprehensive Guide to Application:

This React + TypeScript application is a simple counter app demonstrating the use of the Context API for state management. By using the Context API, the state is efficiently shared and managed across components without the need for prop drilling. This setup showcases a clean and scalable approach to handling the global state in a React application.

By following the below steps, you can easily learn how to use context API and also make an application where you leverage the advantages of context API.

exercise-folder-structure
Let’s understand the folder structure:
  • There is a folder for components, where all the necessary components for the application will be created.
  • There is a folder named assets, where all the styling files will be stored.
  • Then, a separate folder is created for the context.
Therefore, it is good practice to follow a proper folder structure and separate our concerns.
Navigating the Frontend Setup In React:
Let’s start the UI implementation for using React with a TypeScript template. 
  1.  Initializing React Application: To create a React application, you need to start by creating a project folder in your root directory. Inside the project folder, install the necessary dependencies by running the following commands.
npx create-react-app context-api –template typescript
  1. Please follow the below steps to make the theming app using context API for state management. In the project context-api folder, locate the App.tsx file which serves as the entry point for the project.
    1. Create a separate folder for the components where you will create the necessary components.
    2. In that components folder, make a file named Container.tsx and Card.tsx.
    3. Make a separate folder named context. In that folder make a file with the name DarkModeContext.tsx. 
    4. Design the user interface according to your preference using raw CSS or any library of your choice.
				
					//App.tsx

import Container from "./components/Container/Container";
import { DarkModeProvider } from "./context/DarkModeContext";
import './App.css'

function App() {
  return (
    <div className="App">
      <DarkModeProvider>
        <Container />
      </DarkModeProvider>
    </div>
  );
}
export default App;

				
			
  • In the App component, the Container component is wrapped inside the DarkModeProvider, so all the child components will be able to use the context value.
				
					//DarkModeContext.tsx

import React, {
  Dispatch,
  SetStateAction,
  createContext,
  useState,
} from "react";

interface DarkModeContextType {
  darkMode: boolean;
  toggleDarkMode: Dispatch<SetStateAction<boolean>>;
}

const DarkModeContext = createContext<DarkModeContextType>({
  darkMode: false,
  toggleDarkMode: () => {},
});

function DarkModeProvider(props: any) {
  const [darkMode, setDarkMode] = useState(false);

  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
  };

  return (
    <div>
      <DarkModeContext.Provider value={{ darkMode, toggleDarkMode }}>
        {" "}
        {props.children}
      </DarkModeContext.Provider>
    </div>
  );
}

export { DarkModeContext, DarkModeProvider };


				
			
  • This code defines a DarkModeContext using the createContext() method from the React and the    Provider component. The Provider component is then used in the App component, which wraps a child component called Container.
				
					
//Container.tsx

import { useContext } from "react";
import { DarkModeContext } from "../../context/DarkModeContext";
import Card from "../Card/Card";
import "./Container.css";
import DarkMode from "../../assets/images/sun-svgrepo-com.svg";
import LightMode from "../../assets/images/sun-summer-svgrepo-com.svg";

const Container = () => {
  const { darkMode, toggleDarkMode } = useContext(DarkModeContext);
  return (
    <div className={darkMode ? "darkMode" : "lightMode"}>
      <img
        style={{ height: "200px" }}
        onClick={() => toggleDarkMode(darkMode)}
        src={darkMode ? LightMode : DarkMode}
        alt="sun_svg"
      />
      <Card />
    </div>
  );
};
export default Container;


				
			
  • The Container component uses the useContext() hook to access the darkMode and toggleDarkMode values from the DarkModeContext. It then displays the clickable image to toggle between the dark and light mode.
  • To toggle the mode value in the DarkModeContext, you can use the toggleDarkMode() function provided by the context.
  • The toggleDarkMode() function is used to update the dark mode value when the image is clicked.
				
					//Card.tsx

import { useContext } from "react";
import { DarkModeContext } from "../../context/DarkModeContext";

const Card = () => {
  const { darkMode } = useContext(DarkModeContext);

  return (
    <div>
      <h2 style={{ color: darkMode ? "white" : "black" }}>
        {darkMode
          ? "Please turn on the light. It's too dark here..."
          : "It's too bright here. I can't open my eyes..."}
      </h2>
    </div>
  );
};

export default Card;


				
			
  • Here, in the Card component, we are using dardMode value from the DarkModeContext and then applying styling to the elements depending on the value of the darkMode.
excercise-output1
excercise-output2
Conclusion:

In conclusion, the Context API is a powerful feature of React that allows sharing of data among components without the need to pass props manually down through the component tree. Centralizing state management with the Context API can simplify code, enhance performance, and reduce the need for prop drilling, leading to more accessible applications. The creation of context objects using createContext() method and then the use of Provider and Consumer components to share data among components were discussed. Finally, we looked at an example of how to use the Context API in a simple application and how to update the Context. Overall, Context API is a valuable tool that React developers should have in their toolkit.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

July 19, 2023
React with Liferay cover Image
React with Liferay
November 10, 2023
typescript and react with liferay cover image
TypeScript and React with Liferay
March 27, 2024
Authentication and Authorization in React
Loading...

Featured Projects Portfolios

June 19, 2024
Music License Management Portal _ Onboarding & Data Integrity
Music License Management Portal : Onboarding & Data Integrity

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram