Skip to main content
InterviewHubPRO
Section Overview
Q16

Question 16 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

32%
Svelte & SvelteKit (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

Context API in Svelte: `setContext()` vs. `getContext()`.

senior LevelCode ExampleSystem DesignSvelte 5HTTP & REST APIs

In Simple Words: Allows parent components to provide state to deeply nested children without prop-drilling:

svelte
<!-- Parent.svelte -->
<script>
  import { setContext } from 'svelte';
  let theme = $state('dark');
  setContext('app-theme', { getTheme: () => theme, toggle: () => theme = theme === 'dark' ? 'light' : 'dark' });
</script>

<!-- DeepChild.svelte -->
<script>
  import { getContext } from 'svelte';
  const theme = getContext('app-theme');
</script>

<button onclick={theme.toggle}>Theme: {theme.getTheme()}</button>