Hooks are coming to Vue.js version 3.0
Tags: vue, javascript
Published: 2019-08-30 13:29:59

---
title: Hooks are coming to Vue.js version 3.0
published: true
tags: vue, javascript 
canonical_url: https://blog.logrocket.com/hooks-are-coming-to-vue/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/svwctl4xifsvkzxq7pl2.png
---
**Written by [Nwose Lotanna](https://blog.logrocket.com/author/nwoselotanna/)**✏️

This article introduces an experimental Vue feature called Hooks.

## Before you start

This post is suited for developers of all stages including beginners. Here are a few things you should already have before going through this article.

You will need the following in your pc:

- [Node.js version 10.x](https://nodejs.org/en/) and above installed. You can verify if you do by running the command below in your terminal/command prompt:

```jsx
node -v
```

- A code editor: Visual Studio Code is highly recommended
- [Vue’s latest version](https://vuejs.org/), installed globally on your machine
- [Vue CLI 3.0](https://vuejs.org/) installed on your machine. To do this, uninstall the old CLI version first:

```jsx
npm uninstall -g vue-cli
```

then install the new one:

```jsx
npm install -g @vue/cli
```

- Download a Vue starter project [here](https://github.com/viclotana/vue-canvas)
- Unzip the downloaded project
- Navigate into the unzipped file and run the command to keep all the dependencies up-to-date:

```jsx
npm install
```

## Introduction: Hooks

Initially, React components that contain state logic must be a class component. Even though there were already stateless functional components in React there was a need to create components that accommodate state logic without being classes. That was when Hooks was born. Hooks are a way to use state logic inside functional components, thereby eliminating the need for writing classes.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## What is wrong with classes?

There is nothing wrong with classes, to begin with, but the React team found out that [understanding how classes work has been a drawback to React adoption](https://reactjs.org/docs/hooks-intro.html#classes-confuse-both-people-and-machines). It can be difficult to understand and can become ambiguous as your project increases in size and complexity.

### But I don’t normally use classes in Vue JS..

If you are a Vue developer, you might wonder why classes are being discussed as you do not use classes by default in your Vue projects. While this is true, Vue JS lets you use functional components that are stateless with [mixins](https://vuejs.org/v2/guide/mixins.html). With Vue mixins you can define logic or a functionality in a particular file and use and even re-use it in a functional component.

## The problem with mixins

In a [blog post](https://css-tricks.com/what-hooks-mean-for-vue/), some months back, [Sarah Drasner](https://twitter.com/sarah_edo?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor) a very popular Vue core team member wrote about her conversation with [Evan You](https://twitter.com/youyuxi?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor) the creator of Vue JS. Sarah revealed that a mixin cannot consume or use state from another mixin, which makes chaining of encapsulated logic difficult to achieve. This is the mixin limitation that the Vue Hooks solves for.

## Introducing Vue Hooks

Vue Hooks are basically an enhanced version of mixins, if you do not know what mixins are, they are a platform in Vue used to re-use logic between components (you will see a quick demo of mixins in this post). Vue Hooks lets you pass logic from one Hook to another and you can also use state in a Hook from another Hook. So just like in React, Hooks in Vue are defined in functions which can be a cleaner and more flexible way to define and share logic and can return state.

## Demo A: Vue mixins

If you have followed this post from the start, you must have downloaded [the starter project file](https://github.com/viclotana/vue-canvas) and opened it up in your VS Code application. We are going to create a mixin that contains a counter logic and then import it into any component of choice. First, create a folder called mixins in the root directory and create a new file, call it `clickMixin.js` and copy the code block below inside it:

```jsx
export default { 
    data (){
      return{
        count: 1,
        double: 2
      }
    },
    methods: {
      clicked(){
       this.count++; 
       this.double = this.count*2;
      }
    }
  }
```

This mixin contains counter logic and also contains a variable that returns double the count, you see the export statement because it has to be imported into your component of choice. Open your `Test.vue` component and copy the code block below inside it:

```jsx
<template>
  <div> 
    <button v-on:click="clicked()">Button 1</button>
    <h2>{{this.count}}</h2>
    <h2>{{this.double}}</h2>
  </div>
</template>
<script>
import clickMixin from '../Mixins/clickMixin'
export default {
  name: 'Test',
  mixins: [clickMixin]
}
</script>
```

Here you see how mixins are imported and registered under the name, it is a Vue instance property just like data or methods or computed properties. You also see that inside the template that you have access to this in JavaScript as it relates to the mixins (almost like the mixin was defined right inside the component). If you run the application in your dev server it should look like this:

![application with mixin included](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/vuebutton1and2.png?resize=1424%2C548&ssl=1)

When you click button 1, the counter is increased by 1 and the lower figure is double the counter figure just as the template in your code suggests.

## Demo B: Vue Hooks

You can recreate this logic with Vue Hooks easily, the point of the Hooks is to potentially replace mixins in the future. First of all, you have to install the vue-Hooks package with the node package manager. Open a new terminal in VS Code and run:

```jsx
npm install vue-Hooks
```

Then open up your `main.js` file and initialize Hooks with a line of command before the new Vue statement:

```jsx
Vue.use(Hooks);
```

Open the components folder and create a new file inside it, call it `Modal.vue` then navigate back to the root directory and create a new folder called Hooks. Inside the Hooks folder create a new file called `Hooks.js` and copy this code block below into it:

```jsx
import { useData, useMounted, useEffect, useComputed, useUpdated} from 'vue-Hooks'
export default function clickedHook(){
const data = useData({ count:1 })
const double = useComputed(() => data.count * 2)
useMounted(()=> {console.log('mounted')});
useUpdated(()=> {console.log('updated')});
useEffect(()=> {
     console.log('DOM re-renders....')
 });
return {
     data, double
   }
}
```

Just like in React, Vue Hooks borrows the use-prefix syntax and uses it in the Vue way. You also notice that the lifecycle Hooks available for every Vue instance is accessible inside Vue Hooks, some of them are:

- `useData`: handles initialization of data inside your Hook, so the count is initialized inside it
- `useComputed`: this is more like computed properties inside your Hook, so the double computation is done inside it
- `useMounted`: acts exactly like the mounted lifecycle Hook in your Vue instance but for Hooks
- `useUpdated`: acts exactly like the updated lifecycle Hook in your Vue instance but for Hooks
- `useEffect`: this handles logic on DOM re-render

There are other properties you can import, the whole list can be found [here](https://github.com/yyx990803/vue-hooks) on GitHub. You will notice it is exported as a function, open the `modal.vue` file you created earlier and copy this code block below inside it:

```jsx
<template>
  <div> 
    <button v-on:click="data.count++">Button 2</button>
    <h2>{{data.count}}</h2>
    <h2>{{double}}</h2>
  </div>
</template>
<script>
import clickedHook from '../Hooks/Hooks'
export default {
  name: 'Modal',
  Hooks(){
    return clickedHook();
  }
}
</script>
```

Notice that after importing the Hooks file, you can access the data and the double constants earlier defined in the Hook inside this component. We also see that Hooks registration has the same syntax with data registration, with the function set up and the return object inside it.

### ![](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/08/resizedvuebuttons.gif?resize=686%2C300&ssl=1)  
It is important to note that…

- You can go ahead and use Vue Hooks right away (your Vue version must be 2.x)
- There is [speculation that Vue version 3.0 will ship with Vue](https://css-tricks.com/what-hooks-mean-for-vue/#article-header-id-5) Hooks officially
- It is experimental and so should not be used in production yet
- [Read the Sarah Drasner blog post here](https://css-tricks.com/what-hooks-mean-for-vue/) which contains even more examples too

You can use npm or just go to [GitHub with this link](https://github.com/yyx990803/vue-hooks) to get the project repository.

## Conclusion

This has been a quick overview of Hooks in Vue JS and how they might differ from the React Hooks that inspired it. We also highlighted mixins for readers who have not been introduced to the concept and we looked at an illustration using Hooks. Are you excited about Vue Hooks?
* * *
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/hooks-are-coming-to-vue/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [Hooks are coming to Vue.js version 3.0](https://blog.logrocket.com/hooks-are-coming-to-vue/) appeared first on [LogRocket Blog](https://blog.logrocket.com).