React.js Context Tutorial: A Better Way to Store State?

React.js Context Tutorial: A Better Way to Store State?

While creating a component in a typical React app, we end up creating layers of functional components and class components. Much of the time, we end up following a pattern where we pass props to a functional or class component from Grand Parents to Great Grand Children (referring to the hierarchy shown below). There are cases when props are not required at a certain level but are there just to be passed to another component.

We look in to the JavaScript code necessary to allow your React.js application to store state within the Context layer of its architecture.

While creating a component in a typical React app, we end up creating layers of functional components and class components. Much of the time, we end up following a pattern where we pass props to a functional or class component from Grand Parents to Great Grand Children (referring to the hierarchy shown below). There are cases when props are not required at a certain level but are there just to be passed to another component.

We can use React's context pattern to solve this problem. It's based on the Consumer Provider pattern, i.e. a producer *stores *the state and methods to manipulate the state and the consumer can access them whenever necessary.

Demo: Create a React app with create-react-app and remove the boilerplate code.

Now use the ceateContext as shown below (I've named this file provider.js ):

import React from 'react'
export const Context = React.createContext();
class ContextProvider extends React.Component {
state={digit:2}
    render() {
        return (<Context.Provider value={{digit:this.state.digit}} >
            {this.props.children}
        </Context.Provider>)
    }
}
export default ContextProvider

Here we created a Context that is provided by the React.createContext API. We then sore thestate at this level, and provide its schemas as {digit:2}. Then we simply return Context.Provider with props as the value.

Now we modify the index.js file by wrapping the App component in the <Context.Provider> component.

ReactDOM.render(
<ContextProvider>
   <App />
</ContextProvider> , document.getElementById('root'));

Now it is possible to access the state maintained by Context at any level inside the App component without passing it down.

I created a GreatGrandChildren.js file that looks like the below code block:

import React from 'react'
import { Context } from './ContextProvider'
export const GreatGrandChildren = () => {
    return (<React.Fragment>
        <br></br>
        <Context.Consumer>
            {(context) => <span>   GreatGrandChildren {context.digit}</span>}
        </Context.Consumer>
    </React.Fragment>)
}

Here we need to import the Context that we created and render our component as a function inside <Context.Consumer>.

We can now access Context values inside the Consumer at any level. This saves us from performing prop chaining.

Now, if we want to update the state, add a handler method in context, and make it so it can be accessed by the consumer to handle the state value, we need to modify the context provider's code to add the handler.

 return (<Context.Provider value={{ digit: this.state.digit, onDigitChange: () =>
         this.setState({ digit: this.state.digit + 1 })
          }} >

And we can access this handler from the consumer by doing the following:

 <Context.Consumer>
            {(context) => <span>   GreatGrandChildren {context.digit}  <button onClick={context.onDigitChange}>increase digit</button></span>}
 </Context.Consumer>

Get the code on GitHub.

reactjs

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

ReactJs Course | How to build a YouTube Clone using ReactJS

Hello, this is a new tutorial series about ReactJs. In this series, I will teach you two important topics. First, I will be teaching you what is ReactJs library and why this is so powerful and expandable. We will see what are the important...

Top Reasons to Choose ReactJS for Front-End Development - Prismetric

Why ReactJS is perfect choice for your next web application? Get to know all about ReactJS development and its benefits in detail for frontend development.

ReactJS Development Services | ReactJS Development Company - Chapter 247 Infotech

Chapter 247 Infotech is a leading ReactJS development company in India, USA, offering ReactJS development services at par to a spectrum of business domains from E-commerce, healthcare to Edutech at

Pagination in ReactJs

There are a lot of resourceful materials online that give good insights into pagination in ReactJs, as well as NPM packages you can easily use