30. Context API
Solving Prop Drilling
In React, data flows top-down via props. If your top-level <App /> holds the currentUser state, and a deeply nested <ProfileAvatar /> needs it, you must pass that prop through 5 layers of intermediate components that don't even use it. This is called Prop Drilling, and it creates messy code. The Context API solves this by allowing you to "teleport" data anywhere in the tree.
1. Creating the Context
First, you must create a Context object. This acts as a pipeline for your data.
2. Providing the Context
Next, you wrap the top-level parent component in a Provider. Any component sitting inside this Provider will have access to the data, no matter how deep it is nested.
3. Consuming the Context
Deep down in the component tree, you can pull the data directly out of the Context using the useContext hook, bypassing all the middleman components completely.
Knowledge Check
Ready to test your understanding of 30. Context API?