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:
What is the Vue Composition API?
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.
Inefficient component reuse pattern and logic
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.
As components get larger, readability declines
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.
What are React Hooks?
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:
Hard reuse of stateful logic between components
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> ); }
Complex components are hard to understand
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.
Classes confusing both people and machines
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.
Vue Composition API vs. React Hooks
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 itsvalue
propertyReactive
takes an object as its input and returns a reactive proxy of that function
React 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 components
useEffect(()=> { 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> );
Conclusion
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.
The post Vue Composition API vs. React Hooks appeared first on LogRocket Blog.