How to Avoid Prop Drilling in Svelte
You can avoid prop drilling in Svelte with the use of setContext
and getContext
. You can set a context in a parent component and reach it in any deeply nested child component in the following way:
Copied to clipboard!
<!-- Setting context in parent component -->
<script>
import { setContext } from 'svelte';
setContext(βglobalContext', { ... });
</script>
<!-- Getting the context in a child component -->
<script>
import { getContext } from 'svelte';
const context = getContext('globalContext');
</script>
Note that context is not reactive. If you need to have a reactive behavior, you should pass a store to the context.
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews