normally hme jab koi data kisi child se dusre child tak bhejna hota hai to hm pehle use parent mai pass karte hai or phir parent se use dusre child mai pass karte hai .
But with the help of context we will pass the data directly from one child to another child
So we made a new folder for the context related stuff named “Store”
then create a new file subcription-context.js // this name can be anything as we dont use it as component
Now here React.createContext( initial value) // This will return a object
waise react mai saare functions ek object hi return karte hai that’s why unhe ek hi element mai wrap karne ki jarurat padti hai taaki wo saare individual as object saari hierarchy ko maintain karte hai
Now ab hm jin element ko is context ka acess dena chahte hai ( jo iski value ko use karega no matter wo parent ka child ho ya sibling element )
we have to wrap those elements with <SubcriptionContext.Provider> // here the name should be same as the exported one in the subcription-context.js file
yaha par SubcriptionChart aur SubscriptionList dono components SubcriptionContext k data ko use kar sakte hai ( hme parent aur child k relation k through bhejne ki jarurat nahi hai )
Now hmne ye dekha ki context ki value ki acess kisi element ko kaise deni hai but ab us value ko wo element use karega kaise ?? ( means how a element can listen to the context)
There are two method of listening the context data:
- context consumer
- react hook
1. Context Consumer
Now when we use context consumer we have to wrap the template in the ( using tags like SubscriptionChart or SubscriptionList
<SubscriptionContext.Consumer> {(ctx)=>{ // your template }} <SubscriptionContext.Consumer>
Now this arrow function has the value provided by the context ( which is an object )
Problems : 1. You are not getting the value so it can be because you haven’t provide any value in the .Provider tag
// you can't give a value to provider which is not initialized in the context <SubcriptionContext.Provider value={{Subscription:[]}}>
2. useContext( )
You can simply use the useContext hook in the provided elements to access the data from the context
const ctx= useContext(SubscriptionContext); // now you can access the value just like with the object bcz context is returning object ctx.Subscription // means the array which we have defined