DEV Community

Discussion on: How to Handle Reactivity in Svelte

Collapse
peerreynders profile image
peerreynders • Edited on

Svelte perhaps makes reactivity the most easy.

import { render } from "solid-js/web";
import { createSignal } from "solid-js";

function Counter() {
  const [x, setX] = createSignal(0);
  const bigX = () => x() * 2;
  const addToCounter = () => setX(x => x + 1);

  return (
    <button type="button" onClick={addToCounter}>{bigX()}</button>
  );
}

function Style() { 
  return (
    <style>{
      `button {
        background: #ffb334;
        border-radius: 8px;
        border: none;
        font-weight: bold;
        cursor: pointer;
        padding: 0.5rem 2rem;
        color: white;
        font-size: 1.5rem;
      }`
   }</style>
 );
}

render(() => <><Style/><Counter /></>, document.getElementById("app"));
Enter fullscreen mode Exit fullscreen mode

Playground

Cobbled together by peeking at

other than that I haven't used Solid.js a lot (I've spent considerably more time with Svelte). Really the most magic here is that x() in bigX tracks bigX() invocations and updates them whenever setX() is executed.

(The big difference to React is that Counter only runs once to set everything up - past that it just plain reactivity.)

Svelte adds reactivity by extending the language with reactive declarations and statements (and lets not forget about stores (Solid's stores)).

Collapse
smpnjn profile image
Johnny Simpson Author

I guess it ultimately comes down to personal preference!