React Summary Day-8
Heyy Everyonee ! This is Day 8 of learning react form Hitesh Sir (Chai Aur Code). Today i learned about the context API, what is it, why it is used and how to used it. Hitesh sir explained it wonderfully, why we need the context API, what was problem it solved. So the problem because of which, contsxt API comes into picture is as follows: Consider we have the admin dashboard, we have <Dashboard /> component, and insidde it, we have two more components, leftSide and rightSide, further on rightSide, there is one more component inside it, Card. So, if we want to give the access of some variable to Card component, then we need to pass the prop to first DAshboard, then RightSide, then Card, and it will get it. But did you see problem here? the problem is that the rightSide dosent need the prop, but as Card is inside rightSide, we have to give prop to RightSide tpo. Its dosent need though we need to handle data inside RightSide component. So to solve this problem, context API comes into picture.
So now we know why contextAPi is introduced and what problem it solves, now we will see how it solves the problem. So what we do is we create context on another file, react provides the method to build a context as createContext. So in createContext, we define the variables, method, we want to give access. And there is Provider, it is also inbuilt in react, what Provider does it , it provides the access of data or variable or function/method, declared inside the createContext.
Now, what we do is, we have one hook, useContext, the Provider provides access of everything written inside createContext to useContext, so using useContext hook, we can access the functions declared in createContext. And what we do to give access of the variable or function, remember we created createContext? we hold it in variable and we simply do variable_name.Provider, to provide context . and we export this variable, then we wrap all the components inside this variable, so now every component declared inside this variable has access to methods we declared, one more thing is, this variable expects the props, props are the values, you want to give access to components declared inside this variable, basically the variable is the tag. inside this tag we declare all the variables, then it gives access to the components declared inside it.
In short, this is what i learned today through one project, dark mode toggler, may it seem easy, but when you do it with context API, its pretty complex, and heavy to digest what is happening around. But overall good experience learning context API. Thanks hitesh sir for making it easyy.
