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
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: