Ilaria  Dugg

Ilaria Dugg

1565924652

What React Hooks Mean for Vue developers

If you have looked at react a long time ago and got scared away by some of its verbosity (I mean you ComponentDidMountComponentWillReceivePropsgetDerivedStateFromProps etc.), have a look again. Hooks take functional components to the next level. And it comes with all the benefits you could imagine, no classes, no this, no boilerplate. Turns out I am not alone on this, as some of these points are also mentioned in the official docs talking about the motivation behind hooks.

Let's compare some common vue things and implement them using react hooks, then list up the pros and cons of each tool. This is not to convince you to drop vue over react, especially seeing that vue is moving in the same direction (more on that at the end). But it is always good to get a sense of how the other frameworks achieve common tasks, as something similar might also become the future of vue.

The component itself

The minimum we need for a vue single file component would be the following setup

// Counter.vue

<template>
<div>0</div>
</template>
<script>
export default {}
</script>

And here is the same thing in react

function Counter() {
return <div>0</div>
}
Note that the react component doesn’t necessarily have to live in its own file, since it’s just a function.

Working with state

Vue

// Counter.vue

<template>
<button @click=“increment”>{{ count }}</button>
</template>
<script>
export default {
data() {
return {
count: 1
}
},
methods: {
increment() {
this.count++
}
}
}
</script>

and react

import { useState } from ‘react’

function Counter() {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

return &lt;button onClick={increment}&gt;{ count }&lt;/button&gt;

}

As you can see, react’s useState returns a tuple with a set function as the second argument. In vue, you can directly set the value to update the state.

With hooks, Whenever our state/props get updated, the Counter method is executed again. Only the first time though it initiates the count variable with 1. That’s basically the whole deal about hooks. This concept is one of the few that you have to understand with hooks.

vue pros/cons

(+) predefined structure

(-) you can not just import something and use it in the template. It has to be laid out in one of the various concepts of vue datamethodscomputed$store etc. This also makes some values needlessly reactive and might cause confusion (why is this reactive? Does it change? Where?)

react pros/cons

(+) It’s just a function

(-) Actually it’s a function that gets executed every time state or props change. That way of thinking is likely no problem for those used to the old stateless functional components of react, but for people who exclusively used vue, a new way of thinking is required. It just doesn’t come off natural at first.

(-) Hooks have various rules on where and how you have to use them.

Passing props

// Counter.vue

<template>
<div>
<h1>{{ title }}</h1>
<button @click=“increment”>{{ count }}</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 1
}
},
props: {
title: String
},
methods: {
increment() {
this.count++
}
}
}
</script>

and react

import { useState } from ‘react’

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

return (
    &lt;&gt;
        &lt;h2&gt;{title}&lt;/h2&gt;
        &lt;button onClick={increment}&gt;{count}&lt;/button&gt;
    &lt;/&gt;
)

}

vue pros/cons

(+) You can be specific about the types of your props (without TS)

(-) access the same way as state (this.xxx), but actually behaves differently (e.g. assigning a new value throws a warning). This makes beginners think they can just go ahead and update props.

react pros/cons

(+) easy to understand -> props are just function arguments

Child components

Let’s extract the button into a child component.

vue

// Button.vue

<template>
<button @click=“$emit(‘handle-click’)”>
{{ value }}
</button>
</template>
<script>
export default {
props: [‘value’]
}
</script>
// Counter.vue

<template>
<div>
<h1>{{ title }}</h1>
<Button @handle-click=“increment” :value=“count” />
</div>
</template>
<script>
import Button from ‘./Button’

export default {
    components: {
        Button,
    },
    data() {
        return {
            count: 1
        }
    },
    props: ['title'],
    methods: {
        increment() {
            this.count++
        }
    }
}

</script>

vue introduces a “new” concept events at this point.

The react counterpart

import { useState } from ‘react’

function Button({value, handleClick}) {
return <button onClick={handleClick}>{value}</button>
}

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

return (
    &lt;&gt;
        &lt;h2&gt;{title}&lt;/h2&gt;
        &lt;Button value={count} handleClick={increment}/&gt;
    &lt;/&gt;
)

}

vue pros/cons

(+) clear separation of concerns

(+) events play very nice with vue devtools

(+) Events come with modifiers that make the code super clean. E.g. @submit.prevent=“submit” < applies event.preventDefault()

(-) weird casing rules

(-) sort of an additional concept to learn (events). Actually events are similar to native events in the browser. One of the few differences would be that they don’t bubble up.

react pros/cons

(+) we are not forced to create separate files

(+) no concepts of events -> just pass the function in as a prop. To update props, you can also just pass in a function as a prop

(+) overall shorter (at least in this derived example)

Some of the pros/cons are contradicting, this is because in the end it all comes down to personal preference. One might like the freedom of react, while others prefer the clear structure of vue.

Slots

Vue introduces yet another concept when you want to pass template to a child component. Let’s make it possible to pass more than a string to the button.

// Button.vue

<template>
<div>
<button @click=“$emit(‘handle-click’)”>
<slot>Default</slot>
</button>
<slot name=“afterButton”/>
</div>
</template>
<script>
export default {}
</script>
// Counter.vue

<template>
<div>
<h1>{{ title }}</h1>
<Button @handle-click=“increment”>
<strong>{{ count }}</strong>
<template v-slot:afterButton>
Some content after the button…
</template>
</Button>
</div>
</template>
<script>
import Button from ‘./Button’

export default {
    components: {
        Button,
    },
    data() {
        return {
            count: 1
        }
    },
    props: ['title'],
    methods: {
        increment() {
            this.count++
        }
    }
}

</script>

<strong>{{ count }}</strong> will go inside <slot></slot> since it is the default/unnamed slot. Some content after the button… will be placed inside <slot name=“afterButton”/>.

And in react

import { useState } from ‘react’

function Button({AfterButton, handleClick, children}) {
return (
<>
<button onClick={handleClick}>
{children}
</button>
<AfterButton />
</>
)
}

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

return (
    &lt;&gt;
        &lt;h2&gt;{title}&lt;/h2&gt;
        &lt;Button value={count} handleClick={increment} AfterButton={() =&gt; 'some content...'}&gt;
            &lt;strong&gt;{ count }&lt;/strong&gt;
        &lt;/Button&gt;
    &lt;/&gt;
)

}

vue pros/cons

(-) slots can be confusing. Especially when you send data from the child component to the slot.

(-) Passing slots down multiple components is even more confusing

(-) another concept to learn

These are consequences of vue using a custom templating language. It mostly works, but with slots it can become complicated.

Slots will get simplified in vue 3

react pros/cons

(+) no new concept - Since components are just functions, just create such a function and pass it in as a prop

(+) Doesn’t even have to be a function. You can save template(jsx) in a variable and pass it around. This is exactly what happens with the special children prop.

Computed fields

Let’s simplify the examples again

// Counter.vue

<template>
<div>
<h1>{{ capitalizedTitle }}</h1>
<button @click=“increment”>{{ count }}</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 1
}
},
props: [‘title’],
computed: {
capitalizedTitle() {
return title.toUpperCase()
}
},
methods: {
increment() {
this.count++
}
}
}
</script>

react

import { useState, useMemo } from ‘react’

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)
const capitalizedTitle = title.toUpperCase()

return (
    &lt;&gt;
        &lt;h2&gt;{capitalizedTitle}&lt;/h2&gt;
        &lt;button onClick={increment}&gt;{count}&lt;/button&gt;
    &lt;/&gt;
)

}

In vue, computed fields serve not one, but two purposes. They keep the template clean and at the same time provide caching.

In react, we can simply declare a variable that holds the desired value to solve the problem of keeping the template clean. (const capitalizedTitle = title.toUpperCase())

In order to cache it as well, we can make use of react’s useMemo hook.

const capitalizedTitle = useMemo(() => title.toUpperCase(), [title])

In the second argument we have to specify the fields required to invalidate the cache if any of the fields’ value changes.

useMemo works like this:

title changes outside of component -> Counter function runs since prop got updated -> useMemo realizes that the title changed, runs the function passed in as the first argument, caches the result of it and returns it.

vue pros/cons

(+) nice and clear separation of concerns

(-) you define computed fields in functions, but access them like state/props. This makes perfect sense if you think about it, but I have received questions about this repeatedly by peers.

(-) There is some magic going on here. How does vue know when to invalidate the cache?

(-) Computed fields serve two purposes

react pros/cons

(+) To keep the template clean, there is no new concept to learn, just save it in a variable, and use that variable in the template

(+) You have control over what gets cached and how

Watch

// Counter.vue

<template>
<button @click=“increment”>{{ capitalizedTitle }}</button>
</template>
<script>
export default {
data() {
return {
count: 1
}
},
watch: {
count() {
console.log(this.count)
}
},
methods: {
increment() {
this.count++
}
}
}
</script>

react

import { useState, useEffect } from ‘react’

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

useEffect(() =&gt; {
    console.log(count)
}, [count])

return (
    &lt;button onClick={increment}&gt;{count}&lt;/button&gt;
)

}

useEffect works pretty much the same way as useMemo, just without the caching part.

setCount -> Counter function runs -> useEffect realizes that the count changed and will run the effect.

vue pros/cons

(+) clean, easily understandable, nailed it!

react pros/cons

(+) You can specify multiple fields instead of just one field

(-) The purpose of useEffect is not as clear as vue’s watch. This is also because useEffect is used for more than one thing. It deals with any kind of side effects.

mounted

Doing something when a component has mounted is a good place for ajax requests.

vue

// Counter.vue

<template>
<button @click=“increment”>{{ capitalizedTitle }}</button>
</template>
<script>
export default {
data() {
return {
count: 1
}
},
mounted() {
// this.$http.get…
},
methods: {
increment() {
this.count++
}
}
}
</script>

and react

import { useState, useEffect } from ‘react’

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

useEffect(() =&gt; {
    // ajax request...
}, [])

return (
    &lt;button onClick={increment}&gt;{count}&lt;/button&gt;
)

}

You can use the same useEffect as before, but this time specify an empty array as the second argument. It will execute once, and since there is no state specified like before ([count]), it will never evaluate a second time.

vue pros/cons

(+) clean and easy.

(-) Initiating something and cleaning up after it has to be in two different methods, which makes you jump unnecessarily and forces you to save variables somewhere else entirely (more on that in a moment)

react pros/cons

(-) Very abstract. I would have preferred a dedicated method for it instead.

(-) useEffect callback is not allowed to return promises (causes race conditions)

(+) clean up in very same function:

Turns out useEffect comes with one rather interesting and neat feature. If you return a function within useEffect, it is used when the component gets unmounted/destroyed. This sounds confusing at first, but saves you some temporary variables.

Look at this

import { useState, useEffect } from ‘react’

function App() {
const [showsCount, setShowsCount] = useState(true);

return (
&lt;div className="App"&gt;
    &lt;button onClick={() =&gt; setShowsCount(!showsCount)}&gt;toggle&lt;/button&gt;
    {showsCount &amp;&amp; &lt;Counter /&gt;}
&lt;/div&gt;
);

}

function Counter({ title }) {
const [count, setCount] = useState(1)
const increment = () => setCount(count+1)

useEffect(() =&gt; {
    const interval = setInterval(() =&gt; {
        increment()
        console.log("interval")
    }, 1000)

    return function cleanup() {
        clearInterval(interval)
    }
}, [])

return (
    &lt;button&gt;{count}&lt;/button&gt;
)

}

The interesting part is inside useEffect. In the same scope we are able to create and clear an interval. With vue, we would have to initiate the variable first somewhere else, so that we can fill it in mounted and cleanup inside destroy.

Others

vue

(+) v-model directive

(+) first party tools like SSR, VueX and vue-router that play very nice with devtools

(+) Scoped CSS out of the box. Super easy to use SCSS

(+) Feels more like traditional web development and makes onboarding easier

react

(+) More and more things become first party and part of the react core library (hooks, code splitting, etc.)

(+) many libraries to choose from

Conclusion

vue limits you in certain ways, but by that, it also structures your code in a clean and consistent way.

React doesn’t limit you much, but in return, you have a lot more responsibility to maintain clean code. This I think became much easier with the introduction of hooks.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Originally published on dev.to

#vue-js #reactjs #javascript

What is GEEK

Buddha Community

What React Hooks Mean for Vue developers
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

sophia tondon

sophia tondon

1621250665

Top React JS Development Company | React JS Development Services

Looking to hire dedicated top Reactjs developers at affordable prices? Our 5+ years of average experienced Reactjs developers comprise proficiency in delivering the most complex and challenging web apps.

Hire ReactJS developers online on a monthly, hourly, or full-time basis who are highly skilled & efficient in implementing new technologies and turn into business-driven applications while saving your cost up to 60%.

Planning to** outsource React web Development services from India** using Reactjs? Or would you like to hire a team of Reactjs developers? Get in touch for a free quote!

#hire react js developer #react.js developer #react.js developers #hire reactjs development company #react js development india #react js developer

Aria Barnes

Aria Barnes

1627031571

React 18: Things You Need To Know About React JS Latest Version

The most awaited version of React 18 is finally out now. Its team has finally revealed the alpha version of React 18 and its plan, though the official launch is still pending. This time the team has tried something and released the plan first to know their user feedback because the last version of React 17 was not that much appreciated among developers.

According to Front-end Frameworks SurveyReact JS has ranked top in the list of most loved frameworks. Thus, the developer communities expect a bit higher from the framework, so they are less appreciative of the previous launch.
ReactJS stats.pngSo, this time React 18 will be a blast. For beginners, the team is working on a new approach. They have called a panel of experts, library authors, educators, and developers to take part in a working group. Initially, it will be a small group.

I am not a part of this release but following the team on their GitHub discussion group. After gathering the information from there, I can say that they have planned much better this time.

React 17 was not able to meet the developer's community. The focus was all primarily centered on making it easier to upgrade React itself. React 18 release will be the opposite. It has a lot of features for react developers.

Read more here: React 18: Things You Need To Know About React JS Latest Version

#hire react js developers #hire react js developers india #react developers india #react js developer #react developer #hire react developers

sophia tondon

sophia tondon

1625803880

Top React JS Development Company | React JS Development Services

Looking to hire top Reactjs developers at affordable prices? Our 5+ years of average experienced Reactjs developers comprise proficiency in delivering the most complex and challenging web apps.

Hire ReactJS developers online on a monthly, hourly, or full-time basis who are highly skilled & efficient in implementing new technologies and turn into business-driven applications while saving your cost up to 60%.

Planning to outsource React Js web Development services using Reactjs? Or would you like to hire a team of Reactjs developers? Get in touch for a free quote!

#hire react js developers #hire reactjs developers #hire react js developer #hire react.js developer #hire react.js developers #hire react developer

Aria Barnes

Aria Barnes

1625232484

Why is Vue JS the most Preferred Choice for Responsive Web Application Development?

For more than two decades, JavaScript has facilitated businesses to develop responsive web applications for their customers. Used both client and server-side, JavaScript enables you to bring dynamics to pages through expanded functionality and real-time modifications.

Did you know!

According to a web development survey 2020, JavaScript is the most used language for the 8th year, with 67.7% of people choosing it. With this came up several javascript frameworks for frontend, backend development, or even testing.

And one such framework is Vue.Js. It is used to build simple projects and can also be advanced to create sophisticated apps using state-of-the-art tools. Beyond that, some other solid reasons give Vuejs a thumbs up for responsive web application development.

Want to know them? Then follow this blog until the end. Through this article, I will describe all the reasons and benefits of Vue js development. So, stay tuned.

Vue.Js - A Brief Introduction

Released in the year 2014 for public use, Vue.Js is an open-source JavaScript framework used to create UIs and single-page applications. It has over 77.4 million likes on Github for creating intuitive web interfaces.

The recent version is Vue.js 2.6, and is the second most preferred framework according to Stack Overflow Developer Survey 2019.

Every Vue.js development company is widely using the framework across the world for responsive web application development. It is centered around the view layer, provides a lot of functionality for the view layer, and builds single-page web applications.

Some most astonishing stats about Vue.Js:

• Vue was ranked #2 in the Front End JavaScript Framework rankings in the State of JS 2019 survey by developers.

• Approximately 427k to 693k sites are built with Vue js, according to Wappalyzer and BuiltWith statistics of June 2020.

• According to the State of JS 2019 survey, 40.5% of JavaScript developers are currently using Vue, while 34.5% have shown keen interest in using it in the future.

• In Stack Overflow's Developer Survey 2020, Vue was ranked the 3rd most popular front-end JavaScript framework.

Why is Vue.Js so popular?

• High-speed run-time performance
• Vue.Js uses a virtual DOM.
• The main focus is on the core library, while the collaborating libraries handle other features such as global state management and routing.
• Vue.JS provides responsive visual components.

Top 7 Reasons to Choose Vue JS for Web Application Development

Vue js development has certain benefits, which will encourage you to use it in your projects. For example, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy increasing popularity compared to other frameworks.

The framework is only 20 kilobytes in size, making it easy for you to download files instantly. Vue.js easily beats other frameworks when it comes to loading times and usage.

Take a look at the compelling advantages of using Vue.Js for web app development.

#1 Simple Integration

Vue.Js is popular because it allows you to integrate Vue.js into other frameworks such as React, enabling you to customize the project as per your needs and requirements.

It helps you build apps with Vue.js from scratch and introduce Vue.js elements into their existing apps. Due to its ease of integration, Vue.js is becoming a popular choice for web development as it can be used with various existing web applications.

You can feel free to include Vue.js CDN and start using it. Most third-party Vue components and libraries are additionally accessible and supported with the Vue.js CDN.

You don't need to set up node and npm to start using Vue.js. This implies that it helps develop new web applications, just like modifying previous applications.

The diversity of components allows you to create different types of web applications and replace existing frameworks. In addition, you can also choose to hire Vue js developers to use the technology to experiment with many other JavaScript applications.

#2 Easy to Understand

One of the main reasons for the growing popularity of Vue.Js is that the framework is straightforward to understand for individuals. This means that you can easily add Vue.Js to your web projects.

Also, Vue.Js has a well-defined architecture for storing your data with life-cycle and custom methods. Vue.Js also provides additional features such as watchers, directives, and computed properties, making it extremely easy to build modern apps and web applications with ease.

Another significant advantage of using the Vue.Js framework is that it makes it easy to build small and large-scale web applications in the shortest amount of time.

#3 Well-defined Ecosystem

The VueJS ecosystem is vibrant and well-defined, allowing Vue.Js development company to switch users to VueJS over other frameworks for web app development.

Without spending hours, you can easily find solutions to your problems. Furthermore, VueJs lets you choose only the building blocks you need.

Although the main focus of Vue is the view layer, with the help of Vue Router, Vue Test Utils, Vuex, and Vue CLI, you can find solutions and recommendations for frequently occurring problems.

The problems fall into these categories, and hence it becomes easy for programmers to get started with coding right away and not waste time figuring out how to use these tools.

The Vue ecosystem is easy to customize and scales between a library and a framework. Compared to other frameworks, its development speed is excellent, and it can also integrate different projects. This is the reason why most website development companies also prefer the Vue.Js ecosystem over others.

#4 Flexibility

Another benefit of going with Vue.Js for web app development needs is flexibility. Vue.Js provides an excellent level of flexibility. And makes it easier for web app development companies to write their templates in HTML, JavaScript, or pure JavaScript using virtual nodes.

Another significant benefit of using Vue.Js is that it makes it easier for developers to work with tools like templating engines, CSS preprocessors, and type checking tools like TypeScript.

#5 Two-Way Communication

Vue.Js is an excellent option for you because it encourages two-way communication. This has become possible with the MVVM architecture to handle HTML blocks. In this way, Vue.Js is very similar to Angular.Js, making it easier to handle HTML blocks as well.

With Vue.Js, two-way data binding is straightforward. This means that any changes made by the developer to the UI are passed to the data, and the changes made to the data are reflected in the UI.

This is also one reason why Vue.Js is also known as reactive because it can react to changes made to the data. This sets it apart from other libraries such as React.Js, which are designed to support only one-way communication.

#6 Detailed Documentation

One essential thing is well-defined documentation that helps you understand the required mechanism and build your application with ease. It shows all the options offered by the framework and related best practice examples.

Vue has excellent docs, and its API references are one of the best in the industry. They are well written, clear, and accessible in dealing with everything you need to know to build a Vue application.

Besides, the documentation at Vue.js is constantly improved and updated. It also includes a simple introductory guide and an excellent overview of the API. Perhaps, this is one of the most detailed documentation available for this type of language.

#7 Large Community Support

Support for the platform is impressive. In 2018, support continued to impress as every question was answered diligently. Over 6,200 problems were solved with an average resolution time of just six hours.

To support the community, there are frequent release cycles of updated information. Furthermore, the community continues to grow and develop with backend support from developers.



Wrapping Up

VueJS is an incredible choice for responsive web app development. Since it is lightweight and user-friendly, it builds a fast and integrated web application. The capabilities and potential of VueJS for web app development are extensive.

While Vuejs is simple to get started with, using it to build scalable web apps requires professionalism. Hence, you can approach a top Vue js development company in India to develop high-performing web apps.

Equipped with all the above features, it doesn't matter whether you want to build a small concept app or a full-fledged web app; Vue.Js is the most performant you can rely on.

Original source

 

#vue js development company #vue js development company in india #vue js development company india #vue js development services #vue js development #vue js development companies