Skip to content

Broken reactivity in context with state #17979

@hyunbinseo

Description

@hyunbinseo

Describe the bug

// src\lib\context.ts
import { createContext } from 'svelte';

export type Ctx = { a?: string; b?: string };

export const [getCtx, setCtx] = createContext<Ctx>();
<!-- src\routes\+layout.svelte -->
<script lang="ts">
  import { setCtx, type Ctx } from '$lib/context';
  import './layout.css';

  let { children } = $props();

  const ctx = $state<Ctx>({});
  setCtx(ctx);
</script>

{#if !!ctx.a && !ctx.b}
  <p><code>b</code> is not set</p>
{:else}
  <pre>{JSON.stringify(ctx)}</pre>
  {@render children()}
{/if}
<!-- src\routes\(group)\+layout.svelte -->
<script>
  import { getCtx } from '$lib/context';

  const ctx = getCtx();
  ctx.a = crypto.randomUUID();
</script>

When loading / through src\routes\(group)\+page.svelte:

  1. ctx is changed from {} to { "a": "<uuid>" }
  2. !!ctx.a && !ctx.b is changed from false to true
{#if !!ctx.a && !ctx.b}
  <!-- This block should be rendered -->
{:else}
  <!-- But this is rendered instead -->
{/if}

Reproduction

https://github.com/hyunbinseo/svelte-kit-templates/tree/svelte-kit-15564

System Info

System:
  OS: Windows 11 10.0.26200
  CPU: (8) x64 Intel(R) Core(TM) Ultra 7 258V
  Memory: 5.22 GB / 31.48 GB
Binaries:
  Node: 24.14.0 - C:\Users\hyunb\AppData\Local\fnm_multishells\10676_1773894686175\node.EXE
  npm: 11.9.0 - C:\Users\hyunb\AppData\Local\fnm_multishells\10676_1773894686175\npm.CMD
  pnpm: 10.32.1 - C:\Users\hyunb\AppData\Local\fnm_multishells\10676_1773894686175\pnpm.CMD
  Deno: 2.4.0 - C:\Users\hyunb\.deno\bin\deno.EXE
Browsers:
  Chrome: 146.0.7680.80
  Edge: Chromium (140.0.3485.54)
  Firefox: 148.0.2 - C:\Program Files\Mozilla Firefox\firefox.exe
npmPackages:
  @sveltejs/adapter-auto: ^7.0.0 => 7.0.1
  @sveltejs/kit: ^2.55.0 => 2.55.0
  @sveltejs/vite-plugin-svelte: ^6.2.4 => 6.2.4
  svelte: ^5.54.0 => 5.54.0
  vite: ^7.3.1 => 7.3.1

Severity

serious, but I can work around it

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions