Discover how to stop passing data like a hot potato and share it smoothly across your app!
Why context shares data without prop drilling in Svelte - The Real Reasons
Imagine you have a family tree of components in your app. You want to share a favorite recipe from the grandparent component all the way down to the youngest child component. Without context, you have to pass the recipe through every family member in between, even if they don't care about it.
Passing data through every component is like forcing everyone in the family to carry a recipe card, even if they never use it. This makes your code messy, hard to maintain, and easy to break if you forget to pass the data at any step.
Context in Svelte acts like a shared family recipe book placed in the kitchen. Any family member (component) can open it and get the recipe directly, without bothering others to pass it along.
Parent.svelte: <Child recipe={recipe} />
Child.svelte: <Grandchild recipe={recipe} />
Grandchild.svelte: uses recipeParent.svelte: import { setContext } from 'svelte'; setContext('recipe', recipe); Grandchild.svelte: import { getContext } from 'svelte'; const recipe = getContext('recipe');
It lets components share data easily across many layers without cluttering intermediate components with unnecessary props.
Think of a theme color or user login info that many parts of your app need. Context lets you share this info once and access it anywhere, like a family sharing a single cookbook instead of passing pages around.
Prop drilling forces data through every component, even if they don't need it.
Context provides a direct way to share data across component layers.
This keeps your code cleaner, simpler, and easier to maintain.