Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Vue Composition API vs. React Hooks
Syncfusion, Inc. profile imageSuresh Mohan
Suresh Mohan forSyncfusion, Inc.

Posted on • Originally published atsyncfusion.com on

     

Vue Composition API vs. React Hooks

React Hooks were introduced with the React 16.8 update, and since then, they have become a necessity forsingle-page applications. They are a function type that allows you to hook into React state and lifecycle methods.

With the introduction of the Vue 3 update,Vue.js has challenged React with its new Composition API, which can extract pieces of reactive logic and share the code with other components.

This article will compare the Vue Composition API and React Hooks to help you understand the differences and similarities between them.

Way of Rendering

React Hooks are only featured in React functional components. These functional components execute with every rerender.

The following code example demonstrates how to use React Hooks. Initially, import theuseState anduseEffect Hooks from React. Next, use theuseState Hook to add a local state inside the React functional component. Finally, use the changing function ofuseState to increment the value of the count with the help of the buttononClick event. ThisuseEffect runs on every render and will update the document title with its current value.

importReact,{useState,useEffect}from'react';functionExample(){const[count,setCount]=useState(0);useEffect(()=>{document.title=Youclicked${count}times;});return(<div><p>Youclicked{count}times</p><buttononClick={()=>setCount(count+1)}>Clickme</button></div>);/** * when you click 10 times, * document title and paragraph will be displayed as "You clicked 10 times." */}exportdefaultExample;
Enter fullscreen modeExit fullscreen mode

Way of rendering in React HooksIn Vue 3, a component is an object, and it can be defined with thesetup() method introduced with the Composition API. You may feel that the React functional component’s body and Vue’ssetup() operation work similarly. But thesetup() method is only executed once, and it acts as an entry point to the Composition API. With the help of that, we can define a state, and this avoids recreating the state with every call.

The following code example shows only the script part of the Vue component. On top of it, we importedwatchEffect andref to define a variable and keep track of it. Inside the setup component, the price is defined with an initial value. The console log will give the updated value every time the price changes.

<script>import{watchEffect,ref,defineComponent}from"vue";exportdefaultdefineComponent({name:"Store",setup(){constprice=ref(10);watchEffect(()=>console.log(price.value));return{price};},});</script><template><h3>Price</h3><inputv-model="price"id="price"placeholder="edit me"></template>
Enter fullscreen modeExit fullscreen mode

Way of Rendering price valueReactive Objects

useState is famous among the React Hooks and helps us to claim reactive objects. A two-member array represents the ReactuseState , the first being the current value and the second being the function that can change the value.

functionExample(){const[count,setCount]=useState(0);return(<div><p>Youclicked{count}times</p><buttononClick={()=>setCount(count+1)}>Clickme</button></div>);}
Enter fullscreen modeExit fullscreen mode

You can define the reactive object inside the newsetup() component in the Vue Composition API. Unlike in React, you do not need to provide a mutation function(setCount) to change the value.

<template><p>You clicked {{count}} times</p><button@click="count += 1">     Click me</button></template><script>import{ref}from"vue";exportdefault{name:"Hooks",setup(){letcount=ref(0);return{count,};},};</script>
Enter fullscreen modeExit fullscreen mode

Implementing Reactive Objects

React has defined some rules for utilizing Hooks:

  • Hooks must be called on the top level of React function components.
  • Hooks should not be called inside loops, conditions, or nested functions.

Although these rules prevent issues like changing the order of Hooks execution by calling Hooks inside conditional blocks, the default behavior ofsetup() in Vue will prevent them, as it executes before the component is created.

Aesthetics and Readability

Defining the state

Vue draws more lines to perform the same functionality possible with a single line of React code. So yes, React Hooks is a valid choice for an elementary code like this. But when the code is complex, it will be easier to use the Vue Composition API than React Hooks. So, let’s add more variables and examine what looks better.

// Reactconst[name,setName=useState('Apple');const[price,setPrice]=useState(20);const[quantity,setQuantity]=useState(100);// Vuesetup(){return{name:ref('Apple'),price:ref(20),quantity:ref(100)}}
Enter fullscreen modeExit fullscreen mode

So, it’s a win for Vue’s Composition API.

Changing the state

Let’s now see how to update the value of a variable. This comparison might be your decisive point in the battle between React Hooks and the Vue Composition API.

Inside the React function component, we defined a local state calledname with its initial value,Apple. Then, we introduced an input element with anonChange event to change the value.

import{useState}from'react';functionExample(){const[name,setName]=useState('Apple');return(<form><inputtype="text"value=nameonChange={e=>setName(e.target.value)}/><h2>Myfavoritefruitis{name}</h2></form>)}
Enter fullscreen modeExit fullscreen mode

Even though React tries to use native JavaScript whenever possible, Vue has new syntaxes likev-model making the code look pretty. The following example shows how we change the value of the local statename by using an input field.

<script>import{ref}from'vue'exportdefault{setup(){return{name:ref('Apple')}}}</script><template><form><inputtype="text"v-model="name"/><h2>Myfavoritefruitis{{name}}</h2></form></template>
Enter fullscreen modeExit fullscreen mode

The previous code example demonstrates how easily you can change a variable with Vue. The main point is that the Vue code is more precise and readable. Such well-organized code will be handy when debugging.

Handling Side Effects

Examples of side effects include data fetching, setting up a subscription, and manual modification of the DOM. React attempts to handle side effects using theuseEffect Hook.

The followinguseEffect Hook does not use any dependencies. With every render of the function,useEffect will be executed. It continuously updates the document title with the current value of the count state.

importReact,{useState,useEffect}from'react';functionExample(){const[count,setCount]=useState(0);useEffect(()=>{document.title=`You clicked${count} times`;});return(<div><p>Youclicked{count}times</p><buttononClick={()=>setCount(count+1)}>Clickme</button></div>);}
Enter fullscreen modeExit fullscreen mode

The Composition API has two methods for dealing with side effects,watch andwatchEffect. Nevertheless, they have their uses.

When multiple variables change, React’suseEffect allows the developer to keep track of these variables and activate a callback function.watchEffect is something we especially think of with Vue’s Composition API, but it does not keep track of the variable values. To achieve that, we have to use awatch().

The following example shows how to implementwatchEffect. Whenever the price value changes,watchEffect will be executed and give the console log.

<script>import{watchEffect,ref,defineComponent}from"vue";exportdefaultdefineComponent({setup(){constprice=ref(100);watchEffect(()=>console.log(price.value)));return{price};},});</script>
Enter fullscreen modeExit fullscreen mode

Key differences:

  • useEffect  — We can tell when the effects will be active by manually adding dependencies.useEffect should be called inside the component.
Case01:useEffect(()=>{//Runs on every render.});Case02:useEffect(()=>{//Runs only on the first render.},[]);Case03:useEffect(()=>{//Runs with first render OR whenever the dependency value changes.},[prop,state]);
Enter fullscreen modeExit fullscreen mode
  • watch— This works very similar touseEffect. We have to tell it when to run the callback function.
//The callback is called whenever `refA` changes.watch(refA,()=>{console.log(refA.value);});
Enter fullscreen modeExit fullscreen mode
  • watchEffect  — With this, we don’t need to add specific dependencies manually. It will run the callback function whenever the reactive variables we use inside it change. AndwatchEffect works outside of a Vue component.
//The callback is called immediately, and//whenever `refA` or `refB` changes ...watchEffect(()=>{console.log(refA.value);console.log(refB.value);});
Enter fullscreen modeExit fullscreen mode

Note: The main difference is that thewatchEffect starts instantly while thewatch() runs lazily.

Final Thoughts

The basis for everything we discussed throughout this article is JavaScript. So first, we went through the React Hooks and alternatives provided by Vue Composition API.

React does not attempt to deviate much of its code from Vanilla JavaScript. And Vue uses fewer lines of code and less time to perform the same operation that React Hooks does. We realized that the Vue code is more precise and readable, which means it has a higher maintenance capability. If you intend to switch from one to the other or are in the stage of choosing between React and Vue, I hope this article gives you a few insights. Thank you for reading!

TheSyncfusion React suite offers over 70 high-performance, lightweight, modular, and responsive UI components in a single package.

The SyncfusionVue UI components library is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in one package.

For questions, you can contact us through oursupport forum,support portal, orfeedback portal. We are always happy to assist you!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mitya profile image
Dima
  • Location
    Kyiv, Ukraine
  • Joined

Defining the state Vue 2022 (with script setup)

<scriptsetup>import{ref}from'vue'constname=ref('Apple');constprice=ref(20);constquantity=ref(100);</script>
Enter fullscreen modeExit fullscreen mode

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Syncfusion provides third-party UI components for React, Vue, Angular, JavaScript, Blazor, .NET MAUI, ASP.NET MVC, Core, WinForms, WPF, UWP and Xamarin.

More fromSyncfusion, Inc.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp