A real “reactivity” mechanism within the language

Although all major Javascript frameworks can be considered ‘responsive’, since they have the ability to automatically update the DOM when part of the app is updated, this mechanism depends on a specific API that the developer must use to notify the system of changes. For example, notifying the app to update the DOM by changing its state in React demands the use of a specific API (the setState method in class-based components and set hooks in functional components).

Although all major Javascript frameworks can be considered ‘responsive’, since they have the ability to automatically update the DOM when part of the app is updated, this mechanism depends on a specific API that the developer must use to notify the system of changes. For example, notifying the app to update the DOM by changing its state in React demands the use of a specific API (the setState method in class-based components and set hooks in functional components).

// React state with class component

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {counter: 0};
  }

  updateCounter() {
    this.setState(({ counter }) => ({
      counter: counter + 1
    }));
  }

  render() {
    return (
      <div>
     	The counter is: {this.state.counter}
	<button onClick={this.updateCounter}>Increase</button>
      </div>
    );
  }
}

// Vue state

export default {
  data () {
    return {
      counter: 0
    }
  },
  methods: {
    updateCounter () {
      this.counter += 1
    }
  }
}

// Svelte state

let counter = 0
counter++

What is clear is that Svelte controls reactivity directly into vanilla Javascript statements thanks to its internal mechanism and compilation. No API, method, or mechanism is needed to trigger reactivity, but instead a value is assigned to a variable using the assignment operator (=).  Using the REPL environment provided on the Svelte website displays not only the final output of a Svelte code but the compiled version of the code as well. The Svelte compiler will produce something like:

counter += 1; $$invalidate('counter', counter)

in which the call to $$invalidate reports the state variable as changed/updated and checks (in the previously mentioned topographic manner) the dependency graph before surgically updating the DOM – that is, the page in the browser. As stated by Rich Harris, the creator of Svelte: “Svelte 3.0 moves reactivity out of the component API and into the language”.

Leave a comment

Your email address will not be published. Required fields are marked *