Tuesday, 1 February 2022

Chapter6- Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props  that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.


Steps To use Context

👉Create Context object 
      • Create Context.js file import it from react
      • Use React.createContext() . This will return one object so collect it in some variable
      •  So Write this code 
                    var myContext = React.createContext(); 
                    export default Context

👉Provide Context object to parent component;
            This means import Context.js file in Parent component 
👉Provide context object to all children of parent comp using Provider component
            In order to make context object available to all children , wrapped the  immediate children                    selector inside the provider component. say B component is child component then 
             <myContext.Provider>
                <B/>
            </myContext.Provider>

👉Store the data in context object using value props
            To store the data in the context object , Provider will take one props called as value, so pass your state value values to value props 
            <myContext.Provider   value = {this.state}>
                <B/>
            </myContext.Provider>
        
👉Consume required data in child component using Consumer component

        Import context object where we want to consume data.
        Just Like Provider component , we have Consumer component to consume the data
        use  Consumer component like below code. 
         This consumer component takes data from context object & pass it to the first arguments in the                functions. Now call required state data of parent using this 'data' e.g. {data.name} 
          <myContext.Consumer>
                            {
                                    (data) => { 
                                                    <div><p>{data.name}</p></div>
                                                }
                                }
            </myContext.Consumer>


Advantages of Context API
  1. While props drilling technique if some mistakes happen while passing props , data wont receive the last child 
  2. Also if tree structure of components are there, middle components don't required the pros value so in this case we can use Context technique

PostedBy: pankaj_bhakre

No comments:

Post a Comment