0% found this document useful (0 votes)
21 views7 pages

Implementing Global State

Uploaded by

Subhankar Jena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views7 pages

Implementing Global State

Uploaded by

Subhankar Jena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lesson Plan

Implementing Global State

(useContext)
Topics

Introduction
What is Global State in React
What is the need for a global state
Understanding useContext() hoo
Working useContext() hook

Introduction

Global state management is crucial to building robust and scalable React applications. While various state
management solutions are available, the useContext hook provides a simple and elegant way to handle the
global state. In this module, we will explore implementing global state management using useContext and how
it can streamline your React application's state management.

What is Global State in React?

Full Stack Web Development


Global state refers to data that needs to be shared and accessed by multiple components throughout your
React application. Managing this state efficiently is essential for maintaining a clean and organized codebase. 

The Context API allows you to create a context that provides a way to pass data through the component tree
without having to pass props manually at every level.

What is the need for a Global State?

Global state in React becomes necessary in various scenarios where you need to share and manage state
across multiple components. Here are some common reasons why the global state might be needed

Sharing Data - When data needs to be accessed by multiple components at different levels of the
component tree
Avoiding Prop Drilling - To avoid passing data through many layers of components via props, which can
make the code harder to maintai
Centralized State Management - For a cleaner and more organized codebase by centralizing state logic in
one location
Dynamic Update - When changes in one part of the application should dynamically update other parts
Decoupling components - To make components more independent and focused on their specific
responsibilities
Simplifying State Management - To simplify the process of reading and updating the state consistently.

Understanding useContext() hook

Full Stack Web Development


The useContext hook is a powerful tool in React that allows you to consume values from a React context
directly without the need for a context consumer. It simplifies the process of accessing the current context
value and subscribing to changes in that value. 

Let's break down the useContext hook and understand how it works
Context - Context provides a way to pass data through the component tree without having to pass props
down manually at every level. It's particularly useful for sharing global state or configuration settings in an
application
Creating a Context - Use the createContext function to create a new context
Providing Context Value - Wrap the part of your component tree that needs access to the context with a
Context.Provide
Consuming Context Value - Components that need access to the context value can use either the
Context.Consumer component or the useContext hook.

Working useContext() hook

Now that we understand something about the Global state and the useContext() Hook, Let's dive deep into
understanding the workings of the useContext hook by creating a simple theme toggle example in React. In this
example, we'll use the useContext hook to toggle between light and dark themes.

Note - create a react app first with the command “npx create-next-app@latest” before following the steps
given below.

Step 1: Create a Theme Context 

First, create a new file called ThemeContext.js where you define your theme context using the createContext
function:

i.e

ThemeContext.js

import { createContext } from 'react';

const ThemeContext = createContext();

export default ThemeContext;

Full Stack Web Development


Step 2: Create a Theme Provider 

Create another file called ThemeProvider.js where you define the ThemeProvider component. This component
will provide the theme and toggle function using the useState hook:

i.e 

ThemeProvider.js

import React, { useState } from 'react';

import ThemeContext from './ThemeContext';

const ThemProvider = ({ children }) => {

const [isDarkTheme, setIsDarkTheme] = useState(false);

const toggleTheme = () => {

setIsDarkTheme((prevTheme) => !prevTheme);

};

return (

<ThemeContext.Provider value={{ isDarkTheme, toggleTheme }}>

{children}

</ThemeContext.Provider>

);

};

export default ThemProvider;

Step 3: Use the ThemeProvider in Your App

In your main App.js file, use the ThemeProvider to wrap your application and provide the theme context to its
children:

i.e

App.js

// App.js

import React from 'react';

import './App.css';

import ThemeProvider from './ThemeProvider';

import ThemedComponent from './ThemeComponent';

const App = () => {

return (

<ThemeProvider>

<ThemedComponent />

</ThemeProvider>

);

};

export default App;

Full Stack Web Development


Step 4: Create a Themed Component

Now, create a component called ThemedComponent.js that consumes the theme using the useContext hook:

i.e 

ThemedComponent.js

// ThemedComponent.js

import React, { useContext } from 'react';

import ThemeContext from './ThemeContext';

const ThemedComponent = () => {

const { isDarkTheme, toggleTheme } = useContext(ThemeContext);

return (

<div className={`app ${isDarkTheme ? 'dark-theme' : 'light-


theme'}`}>

<h1>{isDarkTheme ? 'Dark Theme' : 'Light Theme'}</h1>

<button onClick={toggleTheme}>Toggle Theme</button>

</div>

);

};

export default ThemedComponent;

Step 5: Adding some Styling

Create a simple CSS file (e.g., styles.css) to style your themed component:

App.css

.app {

text-align: center;

padding: 50px;

transition: background-color 0.3s ease-in-out;

.light-theme {

background-color: #f8f8f8;

color: #333;

.dark-theme {

background-color: #333;

color: #fff;

/* styles.css */

.app {

text-align: center;

padding: 50px;

transition: background-color 0.3s ease-in-out;

.light-theme {

background-color: #f8f8f8;

color: #333;

.dark-theme {

background-color: #333;

color: #fff;

Full Stack Web Development


Step 6: Import the CSS in Your App

Import the CSS file in your main App.js file:

App.js

import React from 'react';

import './App.css';

import ThemeProvider from './ThemeProvider';

import ThemedComponent from './ThemeComponent';

const App = () => {

return (

<ThemeProvider>

<ThemedComponent />

</ThemeProvider>

);

};

export default App;

Step 7: Run Your React App

Start your React application, and you should see a themed component that toggles between light and dark
themes when you click the "Toggle Theme" button.

npm start

Browser output - 

Before clicking on the Theme toggle

After clicking on the theme toggler 

The above example demonstrates how the useContext hook is used to consume the theme context in the
ThemedComponent without the need for prop drilling, making the code clean and maintainable.

Full Stack Web Development

You might also like