
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;
In 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>
Reactive 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>);}
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>
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)}}
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>)}
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>
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>);}
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>
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]);
- 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);});
- 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);});
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)
For further actions, you may consider blocking this person and/orreporting abuse