The Vue Composition API and React hooks are both sets of functions that handle state and the reuse of logic in components.
In this article, we’ll compare the Vue Composition API to React Hooks and examine the role each plays in its respective ecosystem.
We’ll discuss the following:
The Vue Composition API is a set of additive, function-based APIs that facilitate flexible composition and maintenance of component logic as it get larger. It was introduced to address some drawbacks associated with using the Options API to create components, especially large components.
Let’s examine some of the issues associated with the Options API and show how the Vue Composition API helps solve these problems.
Vue mixins come in handy when you want to feed your component data that needs to be reused in other components. Mixins are flexible when distributing reusable functionalities for Vue.js components. They can contain any component option, as long as it has been used in that component.
The ideal of mixin works perfectly when working with small-scale applications. As your project gets larger, you may need to create more mixins to handle other kinds of data that will also be reused in other components.
The Vue Composition API helps solve this issue by enabling you to define whatever function you need in a separate JavaScript file and import it wherever you need to import it to avoid naming conflicts.
Here’s an example:
export default function userInfo(name, UserId) { var object = { name: name, age: age }; return object; }
You can then export the user details wherever you want to use it:
<script> import userInfo from './userInfo.js' export default { name: 'app', setup() { const userInfoDetails = userInfo('Favour Woka', '5671'); return { userInfoDetails } } } </script>
Here, we created a separate file and wrote a function that holds a user name and the unique ID and then we imported the user info to the page we want to use. Clearly, this is just a plain JavaScript. The Vue Composition API gives you the flexibility to express yourself.
To explain why readability suffers in larger applications, let’s build a simple calculator using the setup()
method.
Start with the <template>
tag:
<template> <div> <h1>Simple Calculator</h1> <form action=""> <input type="number" v-model="firstAppend" @keyup="addNum()" maxlength="2"> <span class="append"> + </span> <input type="number" v-model="secondAppend" @keyup="addNum()" maxlength="2"> <span> = </span> <span> {{ answer }}</span> </form> </div> </template>
We created an input
tag and bound v-model
to get the value of the input. We also used the @keyup
event listener to listen to the input as the user inputs a value. Finally, we used maxlength
to only accept entries of 2
or less.
<script> import { ref } from 'vue' export default { name: "Home", components: { }, setup() { let firstAppend = ref(0); let secondAppend = ref(0); let answer = ref(0); console.log("A: ",firstAppend.value, secondAppend.value, answer.value) function addNum() { answer.value = parseInt(firstAppend.value?firstAppend.value:"0") + parseInt(secondAppend.value?secondAppend.value:"0"); } return{ firstAppend, secondAppend, answer, addNum } } }; </script>
At the <script>
section, we started by importing ref()
, which takes an argument and returns it with a value
property. Using setup()
, we declared a variable and assigned the value inside the ref()
method to make it reactive. We then returned the value and bound it to the element we wanted to bind it to.
If we look at the input, now we can see that it has a default value of 0
. That’s because we passed a 0
argument in the ref(0)
method. But what if we want to change the value and also get a result?
We could have used component options, such as computed
, data
, or the mounted()
lifecycle Hook to solve this problem. This would work, we would end up writing a ton of code just to solve a simple problem. We can use the setup()
method to solve this problem without adding any other component options. If we were to reuse the same code in another component, we might lose the value.
function addNum() { answer.value = parseInt(firstAppend.value?firstAppend.value:"0") + parseInt(secondAppend.value?secondAppend.value:"0"); }
Here, we made the function addnum()
that was passed as parameter @kepup="addNum"
inside the setup()
method, calculated the value, and returned the function as a value. Now if we type a value inside any input, we’ll get the result printed out immediately as we type.
React Hooks is a new features that was added to React 16.8. Hooks allow us to use state and other React features with out writing a class.
React Hooks was introduced to provide a more direct API concept and to solve drawbacks associated with older versions of React, including:
In older versions of React, there was no attachment for reusable stateful logic behavior between components. Instead, there were patterns such as render props and higher-order components. When sharing data between components, you often had to restructure your components, making code harder to read. With React Hooks, we can solve this by using the useState
and useEffect
Hooks.
Take the following example:
import './App.css'; import { useEffect, useState } from "react"; import Axios from "axios" import Details from './details'; function App() { const [someData, setSomeDate] = useState(""); useEffect(()=> { Axios.get("https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&key=yourkey").then(data => { setSomeDate(data.data.items[0].searchInfo.textSnippet); }) }); return ( <div className="App"> <header className="App-header"> <Details data={someData}/> </header> </div> ); } export default App;
We started by importing useState
and useEffect
from react
and Axios
from axios
. We declared a state variable called someData
and set it to take a string. We can still call those arguments by any name we want to. We also passed in another variable called setSomeData
to update the someData
variable.
Next, we passed an Axios call inside the useEffect
Hook, which tells React that we need an effect to update our DOM.
Once the API call is successful, we set the value to setSomeDate
, which will now update the someDate
variable we created. Now we can share the value to other components easily.
After we returned the value, which is now someDate
, we bound the value to a component and, inside the component, rendered it.
import React from "react"; export default function Details({data}) { console.log(data) return ( <div> <p>Bread hip hop hip</p> <h2>{data}</h2> </div> ); }
React Hooks makes it easier understand your component when it becomes complex. With Hooks, you can split one component into smaller functions.
Just like the previous example, we fetched the Axios API on the app.js
component and made use of the data at another component.
Before React Hooks, we couldn’t break components into smaller ones because the stateful logic was all over the place. Most often, we resort to combining React with a separate state management library to break some of our component.
Finally, React Hooks fixed issues associated with conflicting classes, which facilitates code reuse and improves code organization. Now you can use more React features without class.
React Hooks and Vue Composition API are both sets of functions. Though they handle things differently, both aim to achieve the same thing e.g The reuse of logic between components, readability of larger component etc.
The difference between the Vue Composition API and React Hooks is that React Hooks can run multiple times during rendering; Vue’s setup
function runs only once while creating a component.
The Vue Composition API provides two states:
Ref()
returns an object whose inner value can be accessed by its value
propertyReactive
takes an object as its input and returns a reactive proxy of that functionReact Hooks also provides two hooks:
useState
enables you to add React state to function components:const [someData, setSomeDate] = useState("");
useEffect
lets you perform side effects in function componentsuseEffect(()=> { Axios.get("https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&key=AIzaSyAGdE2qCnOPJsg6du5r99cu1NS01jPsY9g").then(data => { console.log(data.data.items[0]) setSomeDate(data.data.items[0].searchInfo.textSnippet); }) }); return ( <div > {someData} </div> );
In this Vue Composition API tutorial, we explained the reason behind the new features that have been added to Vue.js and React and reviewed the problems these features were designed to fix. We also walked through how to use the Vue Composition API and React Hooks with examples and reviewed the major differences between the Vue Composition API and React Hooks.
To learn more, check out the Vue Composition API and React Hooks documentation.
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps, including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps — start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowIt’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
3 Replies to "Vue Composition API vs. React Hooks"
“we set the value to setSomeDate, which will now update the someDate variable we created. Now we can share the value to other components easily.”
You must be insane, you can’t share local component state to other components by a component scoped useState. If you want to share it with other components you need a global store, whether it’s a context or redux.
Hi, why not make a podcast episode of this one? 🙂
useEffect with no dependencies in this scenario will make an infinity loop