What is Context in React ? : Comprehensive Guide [ For Freshers and Experience ]
what-is-context-in-react-ACTE

What is Context in React ? : Comprehensive Guide [ For Freshers and Experience ]

Last updated on 17th Dec 2021, Blog, General

About author

Vipin Chandra (Deputy Manager )

Vipin Chandra, the Deputy Manager, has more than seven years of experience in the industry. She is proficient in domains such as the ABC analysis, SPI, Factory Overhead, R&D Capex, sunk cost, economic order quantity (EOQ), and EAC.

(5.0) | 19525 Ratings 564

React Context is a method to pass props from parent to child component(s), by storing the props in a store(similar in Redux) and using these props from the store by child component(s) without actually passing them manually at each level of the component tree.

    • Introduction to Context in React
    • After you use context react
    • How do I use React context?
    • Before You Use Context
    • API
    • Why Do We Need The Context API?
    • What problems does React context solve?
    • Conclusion

    Subscribe For Free Demo

      Introduction to Context in React:

      Content provides a way to transfer data to a component tree without lowering props at all levels.

      In the standard React app, data is passed down (parent to child) by props, but such usage may be difficult for certain types of resources (e.g. local preferences, UI theme) required by most components within the application. The context provides a way to share similar values ​​between components without explicitly transferring support to all levels of the tree.


      After you use context react:

      The content is meant to share information that may be thought of as “global” in the React part tree, like the present verified user, theme, or most well-liked language. as an example, within the code below we tend to search within the “theme” prop to vogue the Button part:


      • Class app extends React.Component
      • }
      • Toolbar (tools) must take an extra “theme”
      • // and transfer it to ThemedButton. this could be painful
      • // if each single button within the app has to recognize the theme
      • // as a result of it’ll must be transferred to any or all parts.
      • return (
      • );
      • }
      • Class ThemedButton Extends React.Component
      • }
      • By using context, we are able to avoid transferring props to intermediate parts
      • Content permits U.S. to transfer worth to the depth of a part of a tree
      • // while not connecting it expressly to any or all parts.
      • // produce the context of the present theme (by “light” as default).
      • const ThemeContext = React.createContext (‘light’);
      • Class app extends React.Component supplier to transfer the present content to the tree below.
      • // Any half will browse it, notwithstanding however deep.
      • // during this example, we tend to pass “black” because of the current worth.
      • return (
      • );
      • }
      • }
      • // the centre half isn’t needed
      • // downgrade the theme expressly.
      • Toolbar ()
      • Class ThemedButton Extends React.Component {
      • // Assign contextType to browse current theme context.
      • // React can notice the closest Theme supplier on top of and use its worth.
      • // during this example, the present theme says “dark”.
      • static contextType = ThemeContext;
      • give ()
      • }

      How do I use React context?

      Context is an API built into React, starting with React version 16. This means that we can create and apply context directly by importing React into any React project.


      Course Curriculum

      Learn Advanced ReactJS Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      There are four steps to using the React context:

    • Create a theme using the createContext method.
    • Take the content you created and wrap the content provider next to your section tree.
    • Put any value you like on your content provider using value prop.
    • Read that number within any section using the context buyer.
    • Does all of this sound confusing? It is easier than you think.

    • Let’s look at a basic example. In our application, let’s transfer our own name using Context and read it in the nest section: User.

      • import React from ‘react’;
      • export Const UserContext = React.createContext ();
      • export the default application () {
      • return (
      • )
      • }
      • use User () {
      • return (
      • {value => {value} }
      • {/ * prints: Reed * /}
      • )
      • }

      Let’s break down what we do, step by step:

      In addition to our app component, we create the context with React.createContext () and apply the effect to the variable, UserContext. In almost all cases, you will want to export it as we do here because your component will be in another file. Note that we can transfer the original value to our value prop if we call React.createContext ().


      In our app section, we use UserContext. Directly UserContext.Provider. The content created is a two-dimensional object: Provider and Consumer, both components. To reduce our value for every part of our application, we wrap up our provider (in this case, User). In UserContext.Provider, we set the value we want to transfer to our entire tree. We set that equal value prop to do so. In this case, our name (here, Reed).


      For the user, or when we want to consume (or use) what is provided in our context, we use the consumer component: UserContext.Consumer. To use our pass rate, we use what is called the render props pattern. It’s just a job part of the consumer we offer as a prop. And in return for that function, we can come back and use the value


      Before You Use Context:

      Context is principally used once alternative knowledge must be accessed by multiple parts at totally different breeding levels. Using it meagerly as a result makes the use of the half terribly troublesome.

      If you simply wish to avoid overcoming alternative resources at the most levels, part style is sometimes a less complicated resolution than context.

      For example, take into account the User Page section and therefore the avatar size prop some levels below so a deeply embedded Avatar part link will scan it:


      • // … which provides …
      • // … which provides …
      • // … which provides …

      It may feel unnecessary to transfer user props and avatarSize to multiple levels if finally the Avatar part extremely wants it. It’s conjointly annoying that whenever the Avatar half needs some things from the highest, you’ve got to feature them to all or any of the centre levels additionally.


      Another way to resolve this drawback out of context is to transfer the Avatar part itself so intermediate parts don’t must understand avatar users or resources.


      • Worksheet (resources)
      • // Now, we have:
      • // … which provides …
      • // … which provides …
      • // … which provides …

    • With this alteration, solely the highest part of the Page must understand the employment of Link and Avatar user sections with avatarSize.
    • This change of management will build your code cleaner in most cases by reducing the number of resources you would like to navigate your application and supplying you with a lot of management over root parts. Such an amendment, however, isn’t the proper selection altogether; moving the quality over the tree makes those high-level elements harder and forces the lower elements to be a lot more versatile than you may wish.
    • You are not restricted to at least one kid during a specific section. you will succeed several kids, otherwise, you could have many various “spaces” for youngsters, as listed here:

    • Worksheet (resources).

      This pattern is enough in most cases wherever you would like to separate the kid from his or her shut folks. you’ll be able to go additional by providing props if the kid wants contact with the parent before donating.


    • However, generally identical knowledge must be accessed by multiple elements of the tree, additionally at totally different breeding rates. Content permits you to “spread” such knowledge and changes to that, altogether the sections below. Common examples wherever mistreatment context could also be easier than alternative strategies embody managing this location, theme, or knowledge repository.

      API:

      • React.createContext
      • const MyContext = React.createContext (defaultValue);

      Creating content items. Once React interprets the subscription section it’ll scan the present context price from identical suppliers closer than it within the tree.

      The defaultValue argument is merely used if the part doesn’t have an identical supplier higher than the tree. This default range is often helpful for testing components on their own while not folding them. Note: Passing not outlined as supplier price doesn’t cause shopper parts to use the default price.


      Content.Provider

    • Everything content comes with a supplier React part that permits edible parts to purchase discourse changes.
    • The provider Partner accepts the worth of the property to be transferred to the material possession shares of the supplier.
    • One supplier is often connected to multiple purchasers. suppliers are often placed within the nest to extract values ​​from the depths of the tree.
    • All patrons who are of the Provider’s interest can reimburse whenever the worth of the provider changes.
    • Distribution from the supplier to potential patrons (including .contextType and use context) isn’t subject to the shouldComponentUpdate technique, therefore the client has updated even once a part of the root skips the update.

    • Changes are determined by examining new and previous values ​​using the identical rules as Object.is. Be careful

      The manner changes are determined will cause some issues once things blow over like value: see Caveats.

      • Class.contextType
      • MyClass category Extends React.Component {
      • componentDidMount () {
      • let price = this.context;
      • / * produce side-effect improvement using MyContext price * /
      • }
      • componentDidUpdate () {
      • let price = this.context;
      • / * … * /
      • }
      • sectionWillUnmount () {
      • let price = this.context;
      • / * … * /
      • }
      • give () {
      • let price = this.context;
      • / * offer one thing supported the worth of MyContext * /
      • }
      • }
      • MyClass.contextType = MyContext;

      A theme kind feature within the schoolroom is often provided within the Content item created by React.createContext (). using this feature permits you to consume the approximate current price for that variety of Content using this theme. you’ll be able to talk to this in any mode cycle as well as the supply operate


      Note:

      You can solely purchase one context using API. If you would like to scan quiet one see overwhelming Multiple Contexts. If you’re using syntax for experimental community category fields, you’ll be able to use the standing category field to launch your content.


      • MyClass category Extends React.Component {
      • static contextType = MyContext;
      • give () {
      • let price = this.context;
      • / * provide one thing supported price * /
      • }
      • }
      • Context.Customer
      • {value => / * offer one thing supported context price * /}

      The React section that registers for discourse changes. using this section permits you to purchase content inside the space. He wants to work as a baby. The operation retrieves the present content and returns the React node. The argument for {the price|The worth} transferred to the operator is adequate to the prop value of the closest provider of this context higher than the tree. within the absence of a supplier for the higher than context, the worth argument is adequate, the defaultValue transferred to createContext ().


      For example, the subsequent section can seem as MyDisplayName in DevTools:

      • Context.displayName
      • const MyContext = React.createContext (/ * price * /);
      • MyContext.displayName = ‘MyDisplayName’;
      • // “MyDisplayName.Provider” in DevTools
      • // “MyDisplayName.Consumer” in DevTools

      Why Do We Need The Context API?

      We want to make a part of the “conversion theme” that switches between light-weight mode and black mode for our React app. each element should have access to this theme mode so as to write down properly.


      Generally, we’ll give this theme mode for all parts exploitation props and update this theme exploitation the status:

      import React from “react”;
      • import ReactDOM from “react-dom”;
      • application ()
      • );
      • }
      • Text perform () {
      • return (
      • );
      • }
      • const rootElement = document.getElementById (“root”);
      • ReactDOM.render (, rootElement);
      • Copy
      • In the sample code on top of, we tend to create a Text Section that interprets the h1 component. The colour of the h1 component depends on this theme mode. Currently, the theme is blue. we will switch between blue and red themes by default.
      • We will produce a questionable “theme” state exploitation the utilisation of State hook. The utilisation of the State hook can restore this theme price and also the performance we will use to update the theme.
      • const [itimu, setTheme] = React.useState (“blue”);
      • Copy
      • We’ll conjointly add a button item to our app element. This button is going to be wont to convert themes and needs a click-on event handle. So, let’s write the host of a click-through event as follows:
      • const onClickHandler = () =>
      • Now, we would like to line the new theme to Red if this theme is Blue, and contrariwise. rather than employing a statement if, the simplest thanks to trying this is with the assistance of a ternary operator in JavaScript.
      • setTheme (theme === “red”? “blue”: “red”);
      • Copy
      • So now, we’ve got our OnClick host written. Let’s add this button item to the app section:
      • amendment theme
      • Copy
      • Let’s conjointly convert the theme range of the text element into a standing theme.
      • Copy
      • Now, we must always have this:
      • import React from “react”;
      • import ReactDOM from “react-dom”;
      • import “./styles.css”;
      • application ()
      • const onClickHandler = () => {
      • setTheme (theme === “red”? “blue”: “red”);
      • “>
      • return (
      • amendment theme
      • );
      • }
      • Text perform () {
      • return (
      • );
      • }
      • const rootElement = document.getElementById (“root”);
      • ReactDOM.render (, rootElement);

      We can currently switch between our 2 themes. However, if this was an awfully massive application, it might be tough to use the theme to the nested elements and also the code would be worse.

      What problems does React context solve?

      The context of the React helps us to avoid the problem of digging props. Props drilling is a term that you can define when you go through the stage down the stairs to the confined part, through the parts that you do not need.

      Here is an example of digging props. In this application, we have access to the theme data we want to transfer as part of all components of our application.

      As you can see, however, specific app kids, like Header, also have to download theme data using props.

      • export the default application ({theme}) {
      • return (
      • );
      • }
      • Task Title ({theme}) {
      • return (
      • );
      • }

    • The problem is that we dig the theme prop through many components that do not need it immediately.
    • The Head Component does not need a theme without transferring it to its child component. In other words, it would be better for the User, log in and Menu to use these data directly.
    • This is in the context of the React context – we can pass on the props completely and thus avoid the issue of digging for resources.
    ReactJS Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion:

      “The theme provides the simplest way to transfer information to the element tree while not lowering props in any respect.”

      For a lot of elaborated description, it provides you the simplest way to create some information on the market to all or any elements of the element tree in spite of how deep that half is.

      In this article, we have a tendency to learn a lot regarding the React Context API. The Context API has come back to resolve a couple of completely different issues we have a tendency to have in React applications — one among the foremost vital is prop-drilling. We have a tendency to create Associate in Nursing examples by mistreating the Context API within the schoolroom section, so the performance element. Also, we have a tendency to be introduced to a way to use the context hook.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses

    Get Training Quote for Free