DEV Community

Cover image for React, Vue and Svelte: Comparing how to update State
Clément Creusat
Clément Creusat

Posted on

React, Vue and Svelte: Comparing how to update State

Updating state in...

As explained above, React has the setState method. You can use it directly or wrap it in another function to update an attribute.
Svelte updates it directly as you would do with a JavaScript variable because Svelte is just a compiler!
Vue has almost the same syntax, except you access the new value with message.value = 'new value'

Check it out 🚀

React

Link

import { useState } from 'React';

const Component = () => {
  // state
  const [message, setMessage] = useState<string>('Hello');
  const updateMessage = () => setMessage('Hello World');

  return (
    <div>
      { message }
      <button onClick={updateMessage}>Update message<button>
    </div>
  )

}
Enter fullscreen mode Exit fullscreen mode

Vue

Link

<script setup lang="ts">
  import { ref } from 'vue'; 
  // state
  const message:string = ref('hello');

  const updateMessage = () => {
    message.value = 'Hello World';
  }
</script>

<template>
 {{ message }}
 <button @click="updateMessage">Update message</button>
</template>
Enter fullscreen mode Exit fullscreen mode

Svelte

Link

<script lang="ts">
// state
let message:string = 'hello';

const updateMessage = () => {
  message = 'Hello World';
}
<script>

<div>{ message }</div>
<button on:click="updateMessage">Update message</button>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)