Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Have you tried it out? You can definitely move that $state call into a utility function (or a class field, or another file, etc).


I can’t do this:

  const createCounter = () => $state(0);
  let counter = createCounter();
> $state(...) can only be used as a variable declaration initializer or a class field https://svelte.dev/e/state_invalid_placement (state_invalid_placement)

It has to be part of a variable initialization even though it looks like it’s creating a value.


That's correct. Svelte has form for overloading JavaScript syntax with its own additions. This rune is not JavaScript. What it actually is is a flag for the compiler to abstract away the complexity of signals by saying "treat this value as reactive". When it's compiled, it generates all the signals needed to make the value reactive. But the ergonomics of using it are as mostly the same as if you were creating a value. It's not the same though, and so there are warnings in case you use it in a way that the compiler won't handle correctly.


Oh, weird, I could swear I've done that before. Especially weird because a class field is essentially the same thing.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: