Context
-
To pass data from a parent to a child component by attributes. -
Emit events from a child component to inform a parent to run a workflow.
The problem with passing a state
Step 1: Define Context
Step 2: Use the Context
Step 3: Use the Components
Hint: According to the Single responsibility principle , we often use a pattern of context together with slots . The components only job is to provide context, and by using slots you can add it to any other component's children, by wrapping them inside the default slot.
Pros and Cons: Attributes & Events vs. Context
-
Overuse Leads to Unmaintainable Components : Using Context excessively can make the data flow in your application harder to track, leading to less maintainable and understandable components. With attributes and events, the data flow is explicit and easy to follow. -
Component Reusability : Components relying on a lot of Context can become less reusable. These components are tightly coupled with the Context they consume, making them unable to work if their context providers do not exist or have unexpected data. On the other hand, some complex components can become simple plug-and-play as long as their context is available. -
Scalability Concerns : Managing a large global state with Context can become challenging as applications grow. State is effectively complexity, and complexity is the enemy of large apps. Context can both create or remove complexity, depending on the problem you're trying to solve.
Exposing context from a root-level component ( page ) is effectively global state as all other components must be children.