How to Avoid Prop Drilling in Svelte

How to Avoid Prop Drilling in Svelte

Ferenc Almasi β€’ 2020 October 09 β€’ Read time 1 min read
  • twitter
  • facebook

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>
Context.svelte

Note that context is not reactive. If you need to have a reactive behavior, you should pass a store to the context.

How to Avoid Prop Drilling in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into Svelte 3

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.