As a beginner to ReactJS, I was working on a Healthcare application where I wanted to pass data from my Doctor Component to the First Patient Component. What did I do? Followed the usual method of Prop Drilling. I just passed the value from my Doctor component to First Assistance Component, from First Assistance component to First Patient Component. Ufffff!! That was long and tired right…
This took me many lines of code to perform and for bigger applications, it would be a headache. I really found this frustrating and wanted to find an easy way to pass data directly to the specific child component. When I was on the search for an alternative solution, suddenly I got a call and heard the voice say, “I will help you…”
Are you excited to know! Me too…
“Hello! I am Context-API and I can solve your problem. Do you want to know about me? Let me boast about myself…,
I am generally used between Components for Data Communication and will provide you a way to pass data through the component tree without having to pass props down manually at every level. People use me to pass data or value from Parent Component to 4th or 5th Child Component and I will be available at 3 steps.
Step 1 : Create me using Const MyContext = React.createContext().
Step 2: Provide me as a context value using “Provider“.
Step 3 : Consume me as a context value using “Consumer“.
Let me share a chart for a better understanding…
To explain the charts: Earlier, the patient received their health data from the assistants who received it from the main doctor. Data to Doctors to Assistants to Patients was the hierarchy. But now, the patients can directly access their health data from the assigned doctor. This eliminates the step of getting the data from the assistants (i.e.) you can skip one level in the hierarchy and get access to your data (similar to not sending the data to each and every level as in prop drilling).
Hope I have helped you and solved your problem. Call me at any time if you want to pass data between components without getting tired. Bye!”
This is how the call ended and I said Goodbye to prop drilling. Context API is one of the best solutions to avoid prop drilling and I would like all of you to try it too!