Skip to content

Svelte 5: No longer able to construct simple variables within using $effect.pre #13910

@KieranP

Description

@KieranP

Describe the bug

Button class that takes booleans and constructs needed CSS classes, used to work in Svelte4, no longer works in Svelte5.

<script lang="ts">
  import type { Snippet } from 'svelte'

  interface Props {
    label?: string
    outline?: boolean
    active?: boolean
    children?: Snippet
  }

  const {
    label = '',
    outline = false,
    active = false,
    children
  }: Props = $props()

  let classNames: string

  if (active) {
    classNames = 'btn text-body bg-secondary text-nowrap'
  } else {
    classNames = 'btn text-body bg-white text-nowrap'
  }

  if (outline) {
    classNames = `${classNames} btn-outline`
  }
</script>

<button
  type="button"
  class={classNames}
>
  {#if label}
    {label}
  {:else if children}
    {@render children()}
  {:else}
    Cancel
   {/if}
</button>

Under Svelte5, getting error:

`classNames` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates(non_reactive_update)eslint[svelte/valid-compile](https://sveltejs.github.io/eslint-plugin-svelte/rules/valid-compile/)

If I make the classNames variable let classNames = $state(''), then I get this error when trying to replace classNames:

State referenced in its own scope will never update. Did you mean to reference it inside a closure?(state_referenced_locally)eslint[svelte/valid-compile](https://sveltejs.github.io/eslint-plugin-svelte/rules/valid-compile/)

It looks like I need to wrap the code in a $effect.pre block now, which seems like overkill.

  let classNames = $state('')

  $effect.pre(() => {
    if (active) {
      classNames = 'btn text-body bg-secondary text-nowrap'
    } else {
      classNames = 'btn text-body bg-white text-nowrap'
    }

    if (outline) {
      classNames = `${classNames} btn-outline`
    }
  })

Is this expected going forward?

Reproduction

See above

Logs

No response

System Info

System:
    OS: macOS 15.0.1
    CPU: (12) arm64 Apple M3 Pro
    Memory: 68.66 MB / 18.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.15.1 - ~/.asdf/installs/nodejs/20.15.1/bin/node
    Yarn: 4.3.1 - ~/.asdf/installs/nodejs/20.15.1/bin/yarn
    npm: 10.8.2 - ~/.asdf/plugins/nodejs/shims/npm
    bun: 1.1.0 - ~/.bun/bin/bun
  Browsers:
    Chrome: 130.0.6723.70
    Safari: 18.0.1
  npmPackages:
    svelte: ^5.1.2 => 5.1.2

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions