DEV Community

Discussion on: Svelte for React dev

Collapse
 
pengeszikra profile image
Peter Vivo
let count = 0;

function increment() {
  count += 1;
}
Enter fullscreen mode Exit fullscreen mode

In my read: increment function have outer dependency, so this is impure solution.

Collapse
 
fkrasnowski profile image
Franciszek Krasnowski

So is the React one:

function increment() {
  setCount(count + 1);
}
Enter fullscreen mode Exit fullscreen mode

Both setCount and count are outer dependencies. You can do:

function increment() {
  setCount(count => count + 1);
}
Enter fullscreen mode Exit fullscreen mode

But still, hooks are impure by definition. They make components stateful and therefore impure. Svelte takes advantage of being a compiler and instead of writing custom hooks, which are impure. You can use a couple of approaches to make your state more predictable. Like stores:

const count = writable(0)
const increment = () => count.update(count => count + 1)
Enter fullscreen mode Exit fullscreen mode

Where the writable is a regular framework-agnostic store not necessarily bounded to component context, thus you can test it without additional dependencies, hook runners, etc. For example, Svelte spring transitions are handled by stores, not in custom hooks like in react-spring or framer-motion. But in my opinion, the true advantage of Svelte approach is that state mutations are just very terse and "explicit" in Svelte. In React the combination of multiple refs and useEffects sometimes causing me an eyestrain