React Hooks Tutorial for Beginners: Getting Started With React Hooks

React Hooks Tutorial for Beginners: Getting Started With React Hooks


Here I am, writing a React hooks tutorial for you. I decided to wait until hooks got finally released before dropping this post. Together we’ll learn React hooks step by step, with a look at how the same logic would be implemented with ES6 classes.

Enjoy the reading!


React Hooks Tutorial for Beginners: what you will learn

In the following tutorial you’ll learn:

  • how to use React hooks
  • how the same logic would be implemented in React class components

React Hooks Tutorial for Beginners: requirements

To follow along with the tutorial you should have a basic understanding of:

  • ES6 (arrow functions, destructuring, classes)
  • React

React Hooks Tutorial for Beginners: setting up the project

If you want to follow along with the examples make sure to configure a React development environment. Run:

<pre class="ql-syntax" spellcheck="false">npx create-react-app exploring-hooks

</pre>

and you’re good to go!

(You should have one of the latest version of Node.js for running npx).


React Hooks Tutorial for Beginners: in the beginning there was setState

I won’t go too deep here, I assume you’re already using React in your project but let me do a quick recap.

React is a library for building user interfaces and one of its perks is that the library itself imposes a strict data flow to the developer. Do you remember jQuery? With jQuery it’s almost impossible to clearly structure a project, let alone defining how the data should flow across the UI. It’s hard to keep track of what function is changing what piece of UI.

The same applies to plain JavaScript: even if with self-disclipine and practice it’s possibile to come up with a well structured project (thinking about the module pattern), good luck tracking state and interactions between functions (it can be done but it’s hard without external help, see Redux).

These problems has been somewhat eased by React: by enforcing a clear structure (container and functional components) and a strict data flow (components react to state and props change) now its easier than before to create well reasoned UI logic.

So the theory in React is that a piece of UI can “react” in response to a state change. The basic form for expressing this flow was an ES6 class up until now. Consider the following example, an ES6 class extending from React.Component, with an internal state:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from "react";

export default class Button extends Component {
constructor() {
super();
this.state = { buttonText: "Click me, please" };
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(() => {
return { buttonText: "Thanks, been clicked!" };
});
}

render() {
const { buttonText } = this.state;
return <button onClick={this.handleClick}>{buttonText}</button>;
}
}

</pre>

As you can see from the code above the component’s internal state gets mutated by setState when clicking the button. The text’s button in turns reacts to this change and gets the updated text.

A more concise version of the component can be expressed by removing the constructor and leveraging the ECMAScript class field proposal:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from "react";

export default class Button extends Component {
state = { buttonText: "Click me, please" };

handleClick = () => {
this.setState(() => {
return { buttonText: "Thanks, been clicked!" };
});
};

render() {
const { buttonText } = this.state;
return <button onClick={this.handleClick}>{buttonText}</button>;
}
}

</pre>

So, in the beginning there was setState (and still it will be). But keep calm. The style above is perfectly fine and ES6 classes in React won’t go away anytime soon.

But now with React hooks it’s possible to express the flow internal state change -> UI reaction without using an ES6 class.

Follow me into the next section …


React Hooks Tutorial for Beginners: updating the state in React … without setState

So what options do we have for managing the internal state in React now that setState and classes are not a need anymore?

Enter the first and most important React hook: useState. useState is a function exposed by the react package. You will import that function at the top of your files as:

<pre class="ql-syntax" spellcheck="false">import React, { useState } from "react";

</pre>

By importing useState in your code you’re signaling the intent to hold some kind of state inside your React component. And more important, that React component shouldn’t be an ES6 class anymore. It can be a pure and simple JavaScript function. This is the most appealing thing of this hooks story.

After importing useState you’ll pick an array containing two variables out of useState, and the code should go inside your React component:

<pre class="ql-syntax" spellcheck="false">const [buttonText, setButtonText] = useState("Click me, please")

</pre>

Confused by this syntax? It’s ES6 destructuring. The names above can be anything you want, it doesn’t matter for React. Anyway I advise using descriptive and meaningful variable names depending on the state’s purpose.

The argument passed to useState is the actual starting state, the data that will be subject to changes. useState returns for you two bindings:

  • the actual value for the state
  • the state updater function for said state

So the previous example, a button component, with hooks becomes:

<pre class="ql-syntax" spellcheck="false">import React, { useState } from "react";

export default function Button() {
const [buttonText, setButtonText] = useState("Click me, please");

return (
<button onClick={() => setButtonText("Thanks, been clicked!")}>
{buttonText}
</button>
);
}

</pre>

For calling the setButtonText state updater inside the onClick handler you can use an inline arrow function. But if you prefer using a regular function you can do:

<pre class="ql-syntax" spellcheck="false">import React, { useState } from "react";

export default function Button() {
const [buttonText, setButtonText] = useState("Click me, please");

function handleClick() {
return setButtonText("Thanks, been clicked!");
}

return <button onClick={handleClick}>{buttonText}</button>;
}

</pre>

Must be honest, I fancy regular functions more than arrow functions, unless I have specific requirements. Readability improves a lot. Also, when I write code I think always of the next developer that will mantain that code. And my code should be readable.

React hooks, that’s it! I could end this post here but not before showing you how to fetch data with hooks.

Head over the next section!


React Hooks Tutorial for Beginners: in the beginning there was componentDidMount (and render props)

Data fetching in React! Do you remember the old days of componentDidMount? You would slap fetch(url) in componentDidMount and call it a day. Here’s how to fetch an array of data from an API for rendering out a nice list:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from "react";

export default class DataLoader extends Component {
state = { data: [] };

componentDidMount() {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data =>
this.setState(() => {
return { data };
})
);
}

render() {
return (
<div>
<ul>
{this.state.data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}
}

</pre>

You could even use async/await in componentDidMount, with some caveats. But most of the asynchronous logic in my projects would live outside React components. There are yet a couple of shortcomings in the above code. The rendered list is fixed but with a render prop we can easily pass children as a function. The refactored component would look like the following:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from "react";

export default class DataLoader extends Component {
state = { data: [] };

componentDidMount() {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data =>
this.setState(() => {
return { data };
})
);
}

render() {
return this.props.render(this.state.data);
}
}

</pre>

And you would consume the component by providing a render prop from the outside:

<pre class="ql-syntax" spellcheck="false"> <DataLoader
render={data => {
return (
<div>
<ul>
{data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}}
/>

</pre>

Even this pattern (born for providing a nicer alternative to mixins and HOCs) has its shortcomings. And that’s I guess the exact reason which lead React engineers to come up with hooks: provide a better ergonomics for encapsulating and reusing logic in React.

So impatient as I am, one of the first thing I wanted to try with hooks was data fetching. But what hook I’m supposed to use for fetching data? Would the component still use the render prop pattern?

Let’s see into the next section!


React Hooks Tutorial for Beginners: fetching data with useEffect

I thought data fetching with React hooks shouldn’t look so different from useState. A quick glance at the documentation gave me an hint: useEffect could be the right tool for the job.

I read: “useEffect serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API”

Bingo! It’s amazing, isn’t it? With this knowledge in hand I refactored the first version of Dataloader for using useEffect. The component becomes a function and fetch gets called inside useEffect. Moreover, instead of calling this.setState I can use setData (an arbitrary function extracted from useState):

<pre class="ql-syntax" spellcheck="false">import React, { useState, useEffect } from "react";

export default function DataLoader() {
const [data, setData] = useState([]);

useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
});

return (
<div>
<ul>
{data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}

</pre>

At this point I thought “what could be wrong?” and I launched the app. This is what I saw in the console:

It was clearly my fault because I’ve already got an hint of what was going on:

"useEffect serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount"

componentDidUpdate! componentDidUpdate is a lifecycle method running every time a component gets new props, or a state change happens. That’s the trick. If you call useEffect like I did you would see an infinite loop. And for solving this “bug” you would need to pass an empty array as a second argument to useEffect:

<pre class="ql-syntax" spellcheck="false">//

useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
}, []); // << super important array

//

</pre>

I wish this info got the visibility it deserves rather than being at the end of this page: Using the Effect Hook. But even with this informations I wouldn’t suggest rewriting all your React components to use hooks for fetching. A lot could still change in the near future, as Ryan Florence suggests:

Anyway, useEffect replaces componentDidMount, componentDidUpdate, and componentWillUnmount, which I think is a nice thing for both experts developers and newcomers to React.


React Hooks Tutorial for Beginners: can I use render props with React hooks?

Of course! But there’s no point in doing that. Our DataLoader component becomes:

<pre class="ql-syntax" spellcheck="false">import React, { useState, useEffect } from "react";

export default function DataLoader(props) {
const [data, setData] = useState([]);

useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
}, []); // << super important array

return props.render(data)
}

</pre>

And you would consume the component by providing a render prop from the outside as we did in the previous example.

But again, there’s no point in this refactoring because React hooks were born for a reason: sharing logic between components, and we’ll see an example in the next section.


React Hooks Tutorial for Beginners: your first custom React hook

Instead of HOCs and render props, we can encapsulate our logic in a React hook and then import that hook whenever we feel the need. In our example we can create a custom hooks for fetching data.

A custom hook is a JavaScript function whose name starts with “use”, according to the React documentation. Easier done than said. Let’s make a useFetch hook then:

<pre class="ql-syntax" spellcheck="false">// useFetch.js
import { useState, useEffect } from "react";

export default function useFetch(url) {
const [data, setData] = useState([]);

useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, []);

return data;
}

</pre>

And this is how you would use the custom hook:

<pre class="ql-syntax" spellcheck="false">import React from "react";
import useFetch from "./useFetch";

export default function DataLoader(props) {
const data = useFetch("http://localhost:3001/links/");
return (
<div>
<ul>
{data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}

</pre>

This is what make hooks so appealing: finally we have a nice, standardized, and clean way for encapsulating and sharing logic.

NOTE: I didn’t account for fetch errors in the code above, do your homeworks!


React Hooks Tutorial for Beginners: can I use async/await with useEffect?

When playing with useEffect I wanted to try async/await inside the hook. Let’s see our custom hook for a moment:

<pre class="ql-syntax" spellcheck="false">// useFetch.js
import { useState, useEffect } from "react";

export default function useFetch(url) {
const [data, setData] = useState([]);

useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, []);

return data;
}

</pre>

For refactoring to async/await the most natural thing you would do is probably:

<pre class="ql-syntax" spellcheck="false">// useFetch.js
import { useState, useEffect } from "react";

export default function useFetch(url) {
const [data, setData] = useState([]);

useEffect(async () => {
const response = await fetch(url);
const data = await response.json();
setData(data);
}, []);

return data;
}

</pre>

Makes sense right? Then I opened the console and React was screaming at me:

“Warning: An Effect function must not return anything besides a function, which is used for clean-up.” Followed by a complete explanation of what I was doing wrong. How nice!

Turns out you cannot return a Promise from useEffect. JavaScript async functions always return a promise and useEffect should exclusively return another function, which is used for cleaning up the effect. That is, if you were to start setInterval in useEffect you would return a function (we have a closure there) for clearing up the interval.

So for making React happy we could rewrite our asynchronous logic like so:

<pre class="ql-syntax" spellcheck="false">// useFetch.js
import { useState, useEffect } from "react";

export default function useFetch(url) {
const [data, setData] = useState([]);

async function getData() {
const response = await fetch(url);
const data = await response.json();
setData(data);
}

useEffect(() => {
getData();
}, []);

return data;
}

</pre>

and your custom hook will work again.


React Hooks Tutorial for Beginners: wrapping up

React hooks are a nice addition to the library. Born as an RFC in November 2018 they caught up quickly and landed in React 16.8. Think of React hooks as encapsulated states living outside your React components.

React hooks make render props and HOCs almost obsolete and provide a nicer ergonomics for sharing logic. With React hooks you can reuse common pieces of logic between React components.

React ships with a bunch of pre-defined hooks. The most important are useState and useEffect. useState makes possible to use local state inside React components, without resorting to ES6 classes.

useEffect replaces componentDidMount, componentDidUpdate, and componentWillUnmount providing a unified API. There are a lot of other hooks and I suggest reading through the official documentation for learning more.

It’s easy to foresee where React is going: functional components all over the place! But even then we will have 3 ways for expressing components in React:

  • functional components
  • class components
  • functional components with hooks

I can see a lot of convenience in hooks and I’m happy with the API they provide. It’s amazing how React is evolving, the community seems to find always a clever way for solving harder problems.


React Hooks Tutorial for Beginners: resources for learning React hooks

There are a lot of resources out there for learning about React hooks and admittedly some are better than this post. So here are my suggestions.

The React documentation is your first stop for learning hooks: Introducing Hooks is an high level overview of how and why hooks are here. Hooks at a glance goes a bit deeper and it’s the starting point for understanding hooks in depth.

Tania Rascia has a nice introduction on hooks with Build a CRUD App in React with Hooks. Speaking of more advanced use cases Matt Hamlin as a nice write up on useReducer, another React hooks for managing state changes.

Funnily enough useReducer resembles a lot Redux reducers. That’s a proof of how influential Redux is in the React community (that shouldn’t be a surprise since Dan Abramov is behind both Redux and React). I highly suggest learning Redux if you haven’t done yet, it will help a lot before studying useReducer.


React Hooks Tutorial for Beginners: appendix

At the beginning of the article I said: “With jQuery it’s almost impossible to clearly structure a project, let alone defining how the data should flow across the UI”.

And:

“The same applies to plain JavaScript: even if with self-disclipine and practice it’s possibile to come up with a well structured project, good luck tracking application’s state.”

But you might not need React for building user interfaces. Sometimes I build projects with vanilla JavaScript and here I am, doing fine. I use to create a simple prototype without any JavaScript library when I’m not sure what shape the project will take. In these kind of projects I rely on the module pattern for organising the code.

Being able to properly organise and document your code, even with vanilla JavaScript is a valuable asset for every JavaScript developer. For learning more about the module pattern in JavaScript I suggest reading Mastering the module pattern by Todd Motto and JavaScript design patterns by Addy Osmani.

Tracking state changes in the UI is really hard on the other hand. And for this kind of job a lot of libraries had born and die. One of my favorite is Redux and it can be used even with vanilla JavaScript.

Thanks for reading! See you next time!

Originally published on valentinog.com/blog

Keeping your JavaScript code clean forever and scalable

Keeping your JavaScript code clean forever and scalable

JavaScript has its origins in the early web. Starting out as a scripting language, it has now evolved into a fully fledged programming language with support for server-side execution.

Modern web applications rely heavily on JavaScript, especially single-page applications (SPAs). With emerging frameworks like React, AngularJS, and Vue.js, web apps are mainly built with JavaScript.

Scaling these applications — frontend equally as backend — can be quite tricky. With a mediocre setup, you will eventually hit limitations and get lost in a sea of confusion. I want to share a couple of small tips that will help you write clean code in an efficient way.

This article is geared towards JavaScript developers of any skill level. However, developers with at least intermediate knowledge of JavaScript will benefit most from these tips.


1. Isolate your code

The most important thing I can recommend to keep a codebase clean and readable is having specific chunks of logic (usually functions) separated by topic. If you write a function, the function should default to having only one purpose and should not do multiple things at once.

Also, you should avoid causing side effects, meaning in most cases, you should not change anything that is declared outside your function. You receive data into functions with parameters; everything else should not be accessed. If you wish to get something out of the function, return new values.

2. Modularization

Of course, you can group multiple functions into one module (and/or class, if you wish) if these functions are used in a similar way or do similar things. For example, if you have many different calculations to do, split them up into isolated steps (functions) that you can chain. However, these functions can all be declared in one file (module). Here is the example in JavaScript:

function add(a, b) {
    return a + b   
}

function subtract(a, b) {
    return a - b   
}

module.exports = {
    add,
    subtract
}

const { add, subtract } = require('./calculations')

console.log(subtract(5, add(3, 2))

If you are writing frontend JavaScript, definitely make use of default exports for the most important items and named exports for secondary items.

3. Prefer multiple parameters over single object parameters

When declaring a function, you should always prefer multiple parameters over one parameter that expects an object:

// GOOD
function displayUser(firstName, lastName, age) {
    console.log(`This is ${firstName} ${lastName}. She is ${age} years old.`)
}

// BAD
function displayUser(user) {
    console.log(`This is ${user.firstName} ${user.lastName}. She is ${user.age} years old.`)
}

The reason behind this is that you know exactly what you need to pass to the function when you look at the first line of the function declaration.

Even though functions should be limited in size — doing only one job — it may happen that functions grow bigger in size. Scanning through the function body for the variables you need to pass (that are nested inside an object) will take you more time. Sometimes it might seem easier to just use the whole object and pass it to the function, but to scale your application, this setup will definitely help.

There is a certain point where declaring specific parameters does not make sense. For me, it is above four or five function parameters. If your function grows that big, you should pivot to use object parameters.

The main reason here is that parameters need to be passed in a specific order. If you have optional parameters, you need to   pass undefined or null. With object parameters, you can simply pass the whole object, where order and undefined values do not matter.

4. Destructuring

Destructuring is a nice tool that was introduced with ES6. It lets you grab specific fields from an object and assign it to a variable immediately. You can use this for any kind of object or module.

// EXAMPLE FOR MODULES
const { add, subtract } = require('./calculations')

It does make sense to only import the functions you need to use in your file instead of the whole module, and then access the specific functions from it. Similarly, when you decide that you definitely need an object as function parameter, use destructuring as well. This will still give you the overview of what is needed inside the function:

function logCountry({name, code, language, currency, population, continent}) {
    let msg = `The official language of ${name} `
    if(code) msg += `(${code}) `
    msg += `is ${language}. ${population} inhabitants pay in ${currency}.`
    if(contintent) msg += ` The country is located in ${continent}`
}

logCountry({
    name: 'Germany',
    code: 'DE',
    language 'german',
    currency: 'Euro',
    population: '82 Million',
})

logCountry({
    name: 'China',
    language 'mandarin',
    currency: 'Renminbi',
    population: '1.4 Billion',
    continent: 'Asia',
})

As you can see, I still know what I need to pass to the function — even if it is wrapped in an object. To solve the problem of knowing what is required, see the next tip!

(By the way, this also works for React functional components.)

5. Use default values

Default values for destructuring or even basic function parameters are very useful. Firstly, they give you an example of what value you can pass to the function. Secondly, you can indicate which values are required and which are not. Using the previous example, the full setup for the function could look like this:

function logCountry({
    name = 'United States', 
    code, 
    language = 'English', 
    currency = 'USD', 
    population = '327 Million', 
    continent,
}) {
    let msg = `The official language of ${name} `
    if(code) msg += `(${code}) `
    msg += `is ${language}. ${population} inhabitants pay in ${currency}.`
    if(contintent) msg += ` The country is located in ${continent}`
}

logCountry({
    name: 'Germany',
    code: 'DE',
    language 'german',
    currency: 'Euro',
    population: '82 Million',
})


logCountry({
    name: 'China',
    language 'mandarin',
    currency: 'Renminbi',
    population: '1.4 Billion',
    continent: 'Asia',
})

Obviously, sometimes you might not want to use default values and instead throw an error if you do not pass a value. Oftentimes, however, this is a handy trick.

6. Data scarcity

The previous tips lead us to one conclusion: do not pass around data that you don’t need. Here, again, it might mean a bit more work when setting up your functions. In the long run, however, it will definitely give you a more readable codebase. It is invaluable to know exactly which values are used in a specific spot.

7. Line and indentation limit

I have seen big files — very big files. In fact, over 3,000 lines of code. Finding chunks of logic is incredibly hard in these files.

Therefore, you should limit your file size to a certain number of lines. I tend to keep my files below 100 lines of code. Sometimes, it is hard to break up files, and they will grow to 200–300 lines and, in rare occasions, up to 400.

Above this threshold, the file gets too cluttered and hard to maintain. Feel free to create new modules and folders. Your project should look like a forest, consisting of trees (module sections) and branches (groups of modules and module files). Avoid trying to mimic the Alps, piling up code in confined areas.

Your actual files, in comparison, should look like the Shire, with some hills (small levels of indentation) here and there, but everything relatively flat. Try to keep the level of indentation below four.

Maybe it is helpful to enable eslint-rules for these tips!

8. Use prettier

Working in a team requires a clear style guide and formatting. ESLint offers a huge ruleset that you can customize to your needs. There is also eslint --fix, which corrects some of the errors, but not all.

Instead, I recommend using Prettier to format your code. That way, developers do not have to worry about code formatting, but simply writing high-quality code. The appearance will be consistent and the formatting automatic.

9. Use meaningful variable names

Ideally, a variable should be named based on its content. Here are some guidelines that will help you declare meaningful variable names.

Functions

Functions usually perform some kind of action. To explain that, humans use verbs — convert or display, for example. It is a good idea to name your functions with a verb in the beginning, e.g., convertCurrency or displayUserName.

Arrays

These will usually hold a list of items; therefore, append an s to your variable name. For example:

const students = ['Eddie', 'Julia', 'Nathan', 'Theresa']

Booleans

Simply start with is or has to be close to natural language. You would ask something like, “Is that person a teacher?” → “Yes” or “No.” Similarly:

const isTeacher = true // OR false

Array functions

forEachmapreducefilter, etc. are great native JavaScript functions to handle arrays and perform some actions. I see a lot of people simply passing el or element as a parameter to the callback functions. While this is easy and quick, you should also name these according to their value. For example:

const cities = ['Berlin', 'San Francisco', 'Tel Aviv', 'Seoul']
cities.forEach(function(city) {
...
})

IDs

Oftentimes, you have to keep track of the ids of specific datasets and objects. When ids are nested, simply leave it as id. Here, I like to map MongoDB _id to simply id before returning the object to the frontend. When extracting ids from an object, prepend the type of the object. For example:

const studentId = student.id
// OR
const { id: studentId } = student // destructuring with renaming

An exception to that rule is MongoDB references in models. Here, simply name the field after the referenced model. This will keep things clear when populating references documents:

const StudentSchema = new Schema({
    teacher: {
        type: Schema.Types.ObjectId,
        ref: 'Teacher',
        required: true,
    },
    name: String,
    ...
})

10. Use async / await where possible

Callbacks are the worst when it comes to readability — especially when nested. Promises were a nice improvement, but async/await has the best readability, in my opinion. Even for beginners, or people coming from other languages, this will help a lot. However, make sure you understand the concept behind it and do not mindlessly use it everywhere.

11. Module import order

As we saw in tips 1 and 2, keeping logic in the right place is key to maintainability. In the same way, how you import different modules can reduce confusion in your files. I follow a simple structure when importing different modules:

// 3rd party packages
import React from 'react'
import styled from 'styled-components'

// Stores
import Store from '~/Store'

// reusable components
import Button from '~/components/Button'

// utility functions
import { add, subtract } from '~/utils/calculate'

// submodules
import Intro from './Intro'
import Selector from './Selector'

I used a React component as an example here since there are more types of imports. You should be able to adapt that to your specific use case.

12. Get rid of console

console.log is a nice way of debugging — very simple, quick, and does the job. Obviously, there are more sophisticated tools, but I think every developer still uses it. If you forget to clean up logs, your console will eventually end up a giant mess. Then there is logs that you actually want to keep in your codebase; for example, warning and errors.

To solve this issue, you can still use console.log for debugging reasons, but for lasting logs, use a library like loglevel or winston. Additionally, you can warn for console statements with ESLint. That way you can easily globally look for console... and remove these statements.


Cool, isn’t it?

Following these guidelines help to Keep your JavaScript code clean forever and scalable. Are there any tips you find particularly useful? Let us know in the comments what you will include in your coding workflow, and please share any other tips you use to help with code structure!

Thanks for reading, Keep visiting. Hope this post will surely help and you! Please share if you liked it!

Related Articles: Keeping your Vue.js code Clean

React vs. Vue: Which is the Best Choice for 2020?

React vs. Vue: Which is the Best Choice for 2020?

Some of the common queries related to choosing the tech stack are:

  • React or Vue: Which is better for my next web development project?
  • Between. React and Vue which gives better performance?
  • Which among these two javascript technologies is more popular among developers?
  • Which among React and Vue is better for small web applications?
  • Which among the compared javascript framework is more reliable?

After reading the answers to all these questions, you will be able to decide a perfect Javascript technology for your project. Let’s compare React VS Vue on the basis of various parameters to unveil the realities of these programming tools for 2020.

React VS Vue: Popularity

JavaScript is quite quick in launching new frameworks and libraries. In fact, it’s a constant affair and these JavaScript technologies keep exchanging their positions in popularity graphs after every few months.

Let’s look at the latest statistics of 2019 to find out which is more popular between React and Vue.

Stat #1: Google trends: The search trends on Google for Vue and React are depicted in the line graph. React is way ahead in these searches in comparison to Vue.js.

React vs. Vue

Stat #2: Stack Overflow Survey: In the most loved frameworks, React topped the list. But vue.js has also shown remarkable success. Since its launch in 2014, it has become a popular choice for developers in less time.

React vs. Vue

React VS Vue: Background

Let’s get a quick background check for these javascript technologies under this head.

Vue.JS: Evan You, an ex-engineer of Google, created this Javascript framework in 2014. It is not backed by a popular top-notch organization. Version 2.6.10 is its latest release on 20 March’2019.

Its been only five years to its launch which makes it the youngest member of the javascript family. Alibaba and Gitlab are some popular names that are reaping the benefits of this framework. Vue is known as a blend of the features of some successful javascript technologies.

React: Unlike Vue, this javascript library was created by Facebook. Facebook ads traffic management was the major reason behind its creation. It was when Facebook experienced issues in maintenance and coding.

It is well-known for its ability to create dynamic and interactive user interfaces. Version 16.8.6 is React’s latest version which was released on 6th May 2019. Some popular companies writing codes with the help of React are BBC, Instagram, WhatsApp, and the list is actually long!

React VS Vue: Performance

React vs. Vue

The changes in the application are reflected in its user interface and a thing called DOM. There can be a virtual DOM or real DOM. The kind of DOM has a great effect on the performance of any programming technology.

React: It has a virtual DOM which is lightweight and not browser-specific. It is a major reason behind the popularity of React as with virtual DOM, it has eliminated the problem of inefficient performance.

Vue: Vue also has worked with a virtual DOM but provides a faster performance in comparison to React. It also ensures a bug-free performance.

React VS Vue: Community support

Community support is crucial for every software technology. It motivates new users to get committed to a specific technology. Let’s know about the community support for both these technologies.

React: For the maintenance of the increasing ad campaign traffic, Facebook developed this Javascript library. The facebook staff works on adding new and advanced features to React’s functioning. This has provided strong reliability to this library among the react developers.

Vue: It is developed by an ex-google engineer but not backed up by any top brand. This brings a lack of its reliability and an initial boost in the market. But crossing this hurdle, Vue has gained unexpected popularity and support from developers. Vue created its support on its own.

React vs. Vue

React VS Vue: Framework size

React is slightly bigger in size than Vue.js. React is about 100 KB and Vue is of 80 KB in size. The size of frameworks/ libraries can have a significant impact on software development projects.

React needs support for certain tasks from other libraries. One of these tasks is routing. Its small size makes a perfect match for lightweight applications. Vue is even smaller in size which makes it more suitable for the light-weight application.

React VS Vue: Use cases

Before making a choice between the right programming technology, it becomes essential for entrepreneurs to research the kind of companies that are using different tech-stack. Javascript has become an incredible part of the software development services for a long time now.

React vs. Vue

Major credit to this goes to the capabilities of its various frameworks and libraries. So, here are the top use cases of React and Vue:

React:

  • Facebook, as earlier mentioned, ad campaigns of facebook are managed with this technology.
  • Twitter, a social media platform known for its ability to enhance the network quickly.
  • Instagram, a social platform primarily supports photo sharing
  • Whatsapp, a messaging app extensively used all around the globe.

Vue:

  • GitLab is support for developers that allow them to form team codes or copy codes.
  • 9Gag known for sharing of viral memes and another trending content

React VS Vue: Learning Curve

The learning curve is the ability of software developers to apply the codes of a particular language/ framework or library. Between these two programming technologies, Vue is more friendly for web developers according to the statistics.

In Stateofjs research, it was asked to vote for “used it, would use it again” and more respondents voted for React. Apart from that, opinions on other situations were also asked from the respondents.

Here is the representation of responses from the respondents:

React vs. Vue

Refer to this index to understand the above bar graph more clearly.

React vs. Vue

Vue is a new and a must-try framework for web app developers. It is well represented through its score in the option of “heard of it, would like to learn”. This ensures a promising learning curve for this coding technology in the upcoming years.

React VS Vue: Flexibility

React: There is not much to offer in the official react library. Here you get extreme flexibility to choose the tools of your choice. There are some frameworks like angular, everything is provided in its package which does not give enough room to experiment.

Some of the tools that can be integrated with this technology are React routing and Redux and MobX for office management tasks. Well-experienced mobile app developers will enjoy and flourish with this kind of liberty in development as it allows them to create dynamic applications.

Vue: Unlike react, there are certain things provided over the official site of the Vue to the vue.js developers. Moreover, server-side development is also supported by a Vue service side render. To name a few, Vuex for state management and Vue Router for routing are the add-ons that can be used in custom software development services.

Conclusion: React vs Vue

Based on the representation of my above analysis with the help of statistics and facts, we can summarize the following points about React vs Vue:

  • React is more popular and searched programming technology in comparison to Vue.
  • React is backed with a top brand, facebook but Vue is not.
  • React provides more flexibility than Vue.
  • SIze of Vue is smaller than React

At the end of this blog, I assume that your doubts have got cleared regarding the right tech-stack for your application development. If you are still in dilemma then talk to an expert from a reputed web app development company.

For any further assistance from me or in case, if you want to share your personal experience, you can reach me through the comment section at the end.

JavaScript Basics Before You Learn React

JavaScript Basics Before You Learn React

If you already have some experience with JavaScript, all you need to learn before React is just the JavaScript features you will actually use to develop React application. Things about JavaScript you should be comfortable with before learning React are:

It’s the 20% of JavaScript features that you will use 80% of the time, so in this tutorial I will help you learn them all.


Exploring Create React App

The usual case of starting to learn React is to run the create-react-app package, which sets up everything you need to run React. Then after the process is finished, opening src/app.js will present us with the only React class in the whole app:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css';

class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}

export default App;

</pre>

If you never learned ES6 before, you’d think that this class statement is a feature of React. It’s actually a new feature of ES6, and that’s why learning ES6 properly would enable you to understand React code better. We’ll start with ES6 classes.


ES6 Classes

ES6 introduced class syntax that is used in similar ways to OO language like Java or Python. A basic class in ES6 would look like this:

<pre class="ql-syntax" spellcheck="false">class Developer {
constructor(name){
this.name = name;
}

hello(){
return 'Hello World! I am ' + this.name + ' and I am a web developer';
}
}

</pre>

class syntax is followed by an identifier (or simply name) that can be used to create new objects. The constructor method is always called in object initialization. Any parameters passed into the object will be passed into the new object. For example:

<pre class="ql-syntax" spellcheck="false">var nathan = new Developer('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a web developer

</pre>

A class can define as many methods as the requirements needed, and in this case, we have the hello method which returns a string.


Class inheritance

A class can extends the definition of another class, and a new object initialized from that class will have all the methods of both classes.

<pre class="ql-syntax" spellcheck="false">class ReactDeveloper extends Developer {
installReact(){
return 'installing React .. Done.';
}
}

var nathan = new ReactDeveloper('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a web developer
nathan.installReact(); // installing React .. Done.

</pre>

The class that extends another class is usually called child class or sub class, and the class that is being extended is called parent class or super class. A child class can also override the methods defined in parent class, meaning it will replace the method definition with the new method defined. For example, let’s override the hello function:

<pre class="ql-syntax" spellcheck="false">class ReactDeveloper extends Developer {
installReact(){
return 'installing React .. Done.';
}

hello(){
return 'Hello World! I am ' + this.name + ' and I am a REACT developer';
}
}

var nathan = new ReactDeveloper('Nathan');
nathan.hello(); // Hello World! I am Nathan and I am a REACT developer

</pre>

There you go. The hello method from Developer class has been overridden.


Use in React

Now that we understand ES6 class and inheritance, we can understand the React class defined in src/app.js. This is a React component, but it’s actually just a normal ES6 class which inherits the definition of React Component class, which is imported from the React package.

<pre class="ql-syntax" spellcheck="false">import React, { Component } from 'react';

class App extends Component {
// class content
render(){
return (
<h1>Hello React!</h1>
)
}
}

</pre>

This is what enables us to use the render() method, JSX, this.state, other methods. All of this definitions are inside the Component class. But as we will see later, class is not the only way to define React Component. If you don’t need state and other lifecycle methods, you can use a function instead.


Declaring variables with ES6 let and const

Because JavaScript var keyword declares variable globally, two new variable declarations were introduced in ES6 to solve the issue, namely let and const. They are all the same, in which they are used to declare variables. The difference is that const cannot change its value after declaration, while let can. Both declarations are local, meaning if you declare let inside a function scope, you can’t call it outside of the function.

<pre class="ql-syntax" spellcheck="false">const name = "David";
let age = 28;
var occupation = "Software Engineer";

</pre>

Which one to use?

The rule of thumb is that declare variable using const by default. Later when you wrote the application, you’ll realize that the value of const need to change. That’s the time you should refactor const into let. Hopefully it will make you get used to the new keywords, and you’ll start to recognize the pattern in your application where you need to use const or let.


When do we use it in React?

Everytime we need variables. Consider the following example:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from 'react';

class App extends Component {
// class content
render(){
const greeting = 'Welcome to React';
return (
<h1>{greeting}</h1>
)
}
}

</pre>

Since greeting won’t change in the entire application lifecycle, we define it using const here.


The arrow function

Arrow function is a new ES6 feature that’s been used almost widely in modern codebases because it keeps the code concise and readable. This feature allows us to write functions using shorter syntax

<pre class="ql-syntax" spellcheck="false">// regular function
const testFunction = function() {
// content..
}

// arrow function
const testFunction = () => {
// content..
}

</pre>

If you’re an experienced JS developer, moving from the regular function syntax to arrow syntax might be uncomfortable at first. When I was learning about arrow function, I used this simple 2 steps to rewrite my functions:

  1. remove function keyword
  2. add the fat arrow symbol => after ()

the parentheses are still used for passing parameters, and if you only have one parameter, you can omit the parentheses.

<pre class="ql-syntax" spellcheck="false">const testFunction = (firstName, lastName) => {
return firstName+' '+lastName;
}

const singleParam = firstName => {
return firstName;
}

</pre>

Implicit return

If your arrow function is only one line, you can return values without having to use the return keyword and the curly brackets {}

<pre class="ql-syntax" spellcheck="false">const testFunction = () => 'hello there.';
testFunction();

</pre>

Use in React

Another way to create React component is to use arrow function. React take arrow function:

<pre class="ql-syntax" spellcheck="false">const HelloWorld = (props) => {
return <h1>{props.hello}</h1>;
}

</pre>

as equivalent to an ES6 class component

<pre class="ql-syntax" spellcheck="false">class HelloWorld extends Component {
render() {
return (
<h1>{props.hello}</h1>;
);
}
}

</pre>

Using arrow function in your React application makes the code more concise. But it will also remove the use of state from your component. This type of component is known as stateless functional component. You’ll find that name in many React tutorials.


Destructuring assignment for arrays and objects

One of the most useful new syntax introduced in ES6, destructuring assignment is simply copying a part of object or array and put them into named variables. A quick example:

<pre class="ql-syntax" spellcheck="false">const developer = {
firstName: 'Nathan',
lastName: 'Sebhastian',
developer: true,
age: 25,
}

//destructure developer object
const { firstName, lastName } = developer;
console.log(firstName); // returns 'Nathan'
console.log(lastName); // returns 'Sebhastian'
console.log(developer); // returns the object

</pre>

As you can see, we assigned firstName and lastName from developer object into new variable firstName and lastName. Now what if you want to put firstName into a new variable called name?

<pre class="ql-syntax" spellcheck="false">const { firstName:name } = developer;
console.log(name); // returns 'Nathan'

</pre>

Destructuring also works on arrays, only it uses index instead of object keys:

<pre class="ql-syntax" spellcheck="false">const numbers = [1,2,3,4,5];
const [one, two] = numbers; // one = 1, two = 2

</pre>

You can skip some index from destructuring by passing it with ,:

<pre class="ql-syntax" spellcheck="false">const [one, two, , four] = numbers; // one = 1, two = 2, four = 4

</pre>

Use in React

Mostly used in destructuring state in methods, for example:

<pre class="ql-syntax" spellcheck="false">reactFunction = () => {
const { name, email } = this.state;
};

</pre>

Or in functional stateless component, consider the example from previous chapter:

<pre class="ql-syntax" spellcheck="false">const HelloWorld = (props) => {
return <h1>{props.hello}</h1>;
}

</pre>

We can simply destructure the parameter immediately:

<pre class="ql-syntax" spellcheck="false">const HelloWorld = ({ hello }) => {
return <h1>{hello}</h1>;
}

</pre>

Map and filter

Although this tutorial focuses on ES6, JavaScript array map and filter methods need to be mentioned since they are probably one of the most used ES5 features when building React application. Particularly on processing data.

These two methods are much more used in processing data. For example, imagine a fetch from API result returns an array of JSON data:

<pre class="ql-syntax" spellcheck="false">const users = [
{ name: 'Nathan', age: 25 },
{ name: 'Jack', age: 30 },
{ name: 'Joe', age: 28 },
];

</pre>

Then we can render a list of items in React as follows:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from 'react';

class App extends Component {
// class content
render(){
const users = [
{ name: 'Nathan', age: 25 },
{ name: 'Jack', age: 30 },
{ name: 'Joe', age: 28 },
];

return (
  &lt;ul&gt;
    {users
      .map(user =&gt; &lt;li&gt;{user.name}&lt;/li&gt;)
    }
  &lt;/ul&gt;
)

}
}

</pre>

We can also filter the data in the render.

<pre class="ql-syntax" spellcheck="false"><ul>
{users
.filter(user => user.age > 26)
.map(user => <li>{user.name}</li>)
}
</ul>

</pre>

ES6 module system

The ES6 module system enables JavaScript to import and export files. Let’s see the src/app.js code again in order to explain this.

<pre class="ql-syntax" spellcheck="false">import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}

export default App;

</pre>

Up at the first line of code we see the import statement:

<pre class="ql-syntax" spellcheck="false">import React, { Component } from 'react';

</pre>

and at the last line we see the export default statement:

<pre class="ql-syntax" spellcheck="false">export default App;

</pre>

To understand these statements, let’s discuss about modules syntax first.

A module is simply a JavaScript file that exports one or more values (can be objects, functions or variables) using the export keyword. First, create a new file named util.js in the src directory

<pre class="ql-syntax" spellcheck="false">touch util.js

</pre>

Then write a function inside it. This is a default export

<pre class="ql-syntax" spellcheck="false">export default function times(x) {
return x * x;
}

</pre>

or multiple named exports

<pre class="ql-syntax" spellcheck="false">export function times(x) {
return x * x;
}

export function plusTwo(number) {
return number + 2;
}

</pre>

Then we can import it from src/App.js

<pre class="ql-syntax" spellcheck="false">import { times, plusTwo } from './util.js';

console.log(times(2));
console.log(plusTwo(3));

</pre>

You can have multiple named exports per module but only one default export. A default export can be imported without using the curly braces and corresponding exported function name:

<pre class="ql-syntax" spellcheck="false">// in util.js
export default function times(x) {
return x * x;
}

// in app.js
import k from './util.js';

console.log(k(4)); // returns 16

</pre>

But for named exports, you must import using curly braces and the exact name. Alternatively, imports can use alias to avoid having the same name for two different imports:

<pre class="ql-syntax" spellcheck="false">// in util.js
export function times(x) {
return x * x;
}

export function plusTwo(number) {
return number + 2;
}

// in app.js
import { times as multiplication, plusTwo as plus2 } from './util.js';

</pre>

Import from absolute name like:

<pre class="ql-syntax" spellcheck="false">import React from 'react';

</pre>

Will make JavaScript check on node_modules for the corresponding package name. So if you’re importing a local file, don’t forget to use the right path.


Use in React

Obviously we’ve seen this in the src/App.js file, and then in index.js file where the exported App component is being rendered. Let’s ignore the serviceWorker part for now.

<pre class="ql-syntax" spellcheck="false">//index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

</pre>

Notice how App is imported from ./App directory and the .js extension has been omitted. We can leave out file extension only when importing JavaScript files, but we have to include it on other files, such as .css. We also import another node module react-dom, which enables us to render React component into HTML element.

As for PWA, it’s a feature to make React application works offline, but since it’s disabled by default, there’s no need to learn it in the beginning. It’s better to learn PWA after you’re confident enough building React user interfaces.


Conclusion

The great thing about React is that it doesn’t add any foreign abstraction layer on top of JavaScript as other web frameworks. That’s why React becomes very popular with JS developers. It simply uses the best of JavaScript to make building user interfaces easier and maintainable. There really is more of JavaScript than React specifix syntax inside a React application, so once you understand JavaScript better — particularly ES6 — you can write React application with confident. But it doesn’t mean you have to master everything about JavaScript to start writing React app. Go and write one now, and as opportunities come your way, you will be a better developer.

Thanks for reading and I hope you learned some new things :)


Learn More

The Complete JavaScript Course 2019: Build Real Projects!

Become a JavaScript developer - Learn (React, Node,Angular)

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

JavaScript - Step By Step Guide For Beginners

The Web Developer Bootcamp

Modern React with Redux

Become a JavaScript developer - Learn (React, Node,Angular)

The Complete React Web Developer Course (2nd Edition)

Node with React: Fullstack Web Development

Beginner Full Stack Web Development: HTML, CSS, React & Node

How to build a simple ToDo App with React

How to build a simple ToDo App with React

As the topic implies, we are going to be building a To-Do application with React. Do not expect any surprises such as managing state with a state management library like Flux or Redux. I promise it will strictly be React. Maybe in following articles we can employ something like Redux but we want to focus on React and make sure everybody is good with React itself.

Table of Contents

  • Prerequisites
  • Types of Components
  • Recognizing Presentation Components
  • Container Component (Todo App)
  • DOM Rendering
  • Working with a Server
  • Count and Style

Prerequisites

You don't need much requirements to setup this project because we will make use of CodePen for demos. You can follow the demo or setup a new CodePen pen. You just need to import React and ReactDOM library:

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>To-Do</title>
</head>
<body>

    <div class="container">
      <div id="container" class="col-md-8 col-md-offset-2">  </div>
    </div>  

    <script src="https://fb.me/react-15.1.0.js"></script>
    <script src="https://fb.me/react-dom-15.1.0.js"></script>

</body>
</html>

ReactDOM is a standalone library that is used to render React components on the DOM.

Types of Components

There are two types of component. These types are not just react-based but can be visualized in any other component-based UI library or framework. They include:

  • Presentation Component
  • Container Component

Presentation Component: These are contained components that are responsible for UI. They are composed with JSX and rendered using the render method. The key rule about this type of component is that they are stateless meaning that no state of any sort is needed in such components. Data is kept in sync using props.

If all that a presentation component does is render HTML based on props, then you can use stateless function to define the component rather than classes.

Container Component: This type of component complements presentation component by providing states. It's always the guy at the top of the family tree, making sure that data is coordinated.

You do not necessarily need a state management tool outside of what React provides if what you are building does not have too much nested children and less complex. A To-Do is is simple so we can do with what React offers for now provided we understand how and when to use a presentation or container component

Recognizing Presentation Components

It is a recommended practice to have a rough visual representation of what you are about to build. This practice is becomes very important when it comes to component-based designs because it is easier to recognize presentation components.

How to build a simple ToDo App with React

Your image must not be a clean sketch made with a sketch app. It can just be a pencil work. The most important thing is that you have a visual representation of the task at hand.

From the above diagram, we can fish out our presentation components:

  • TodoForm : purple
  • Title: green
  • TodoList: red
  • Todo: grey

Todo Form

Functional components (a.k.a stateless components) are good for presentation components because they are simple to manage and reason about when compared with class components.

For that sake, we will create the first presentation component, TodoForm, with a functional component:

const TodoForm = ({addTodo}) => {
  // Input tracker
  let input;

  return (
    <div>
      <input ref={node => {
        input = node;
      }} />
      <button onClick={() => {
        addTodo(input.value);
        input.value = '';
      }}>
        +
      </button>
    </div>
  );
};

Functional components just receive props (which we destructured with ES6) as arguments and return JSX to be rendered. TodoForm has just one prop which is a handler that handles the click event for adding a new todo.

The value of the input is passed to the input member variable using React's ref.

Todo & Todo List

These components present the list of to-do. TodoList is a ul element that contains a loop of Todo components (made of li elements`):

const Todo = ({todo, remove}) => {
  // Each Todo
  return (<li onClick(remove(todo.id))>{todo.text}</li>);
}

const TodoList = ({todos, remove}) => {
  // Map through the todos
  const todoNode = todos.map((todo) => {
    return (<Todo todo={todo} key={todo.id} remove={remove}/>)
  });
  return (<ul>{todoNode}</ul>);
}

See the Pen AXNJpJ by Chris Nwamba (@christiannwamba) on CodePen.

The remove property is an event handler that will be called when the list item is clicked. The idea is to delete an item when it is clicked. This will be taken care of in the container component.

The only way the remove property can be passed to it's to the Todo component is via it's parent (not grand-parent). For this sake, in as much as the container component that will own TodoList should handle item removal, we still have to pass down the handler from grand-parent to grand-child through the parent.

This is a common challenge that you will encounter in a nested component when building React applications. If the nesting is going to be deep, it is advised you use container components to split the hierarchy.

Title

The title component just shows the title of the application:

const Title = () => {
  return (
    <div>
       <div>
          <h1>to-do</h1>
       </div>
    </div>
  );
}

Container Component (Todo App)

This will eventually become the heart of this application by regulating props and managing state among the presentation components. We already have a form and a list that are independent on each other but we need to do some tying together where needed.

// Contaner Component
// Todo Id
window.id = 0;
class TodoApp extends React.Component{
  constructor(props){
    // Pass props to parent class
    super(props);
    // Set initial state
    this.state = {
      data: []
    }
  }
  // Add todo handler
  addTodo(val){
    // Assemble data
    const todo = {text: val, id: window.id++}
    // Update data
    this.state.data.push(todo);
    // Update state
    this.setState({data: this.state.data});
  }
  // Handle remove
  handleRemove(id){
    // Filter all todos except the one to be removed
    const remainder = this.state.data.filter((todo) => {
      if(todo.id !== id) return todo;
    });
    // Update state with filter
    this.setState({data: remainder});
  }

  render(){
    // Render JSX
    return (
      <div>
        <Title />
        <TodoForm addTodo={this.addTodo.bind(this)}/>
        <TodoList 
          todos={this.state.data} 
          remove={this.handleRemove.bind(this)}
        />
      </div>
    );
  }
}

View CodePen Progress

We first setup the component's constructor by passing props to the parent class and setting the initial state of our application.

Next we create handlers for adding and removing todo which the events are fired in TodoForm component and Todo component respectively. setState method is used to update the application state at any point.

As usual, we render the JSX passing in our props which will be received by the the child components.

DOM Rendering

We have been rendering our demo components to the browser without discussing how but can be seen in the CodePen samples. React abstracts rendering to a different library called ReactDOM which takes your app's root component and renders it on a provided DOM using an exposed render method:

<pre class="ql-syntax" spellcheck="false">ReactDOM.render(<TodoApp />, document.getElementById('container')); </pre>

The first argument is the component to be rendered and the second argument is the DOM element to render on.

Working with a Server

We could step up our game by working with a HTTP server rather than just a simple local array. We do not have to bear the weight of jQuery to make HTTP request, rather we can make use of a smaller library like Axios.

<pre class="ql-syntax" spellcheck="false"><script src="https://npmcdn.com/axios/dist/axios.min.js"></script> </pre>

React lifecycle methods help you hook into React process and perform some actions. An example is doing something once a component is ready. This is done in the componentDidMount lifecycle method. Lifecycle methods are just like normal class methods and cannot be used in a stateless component.

class TodoApp extends React.Component{
  constructor(props){
    // Pass props to parent class
    super(props);
    // Set initial state
    this.state = {
      data: []
    }
    this.apiUrl = 'https://57b1924b46b57d1100a3c3f8.mockapi.io/api/todos'
  }
  // Lifecycle method
  componentDidMount(){
    // Make HTTP reques with Axios
    axios.get(this.apiUrl)
      .then((res) => {
        // Set state with result
        this.setState({data:res.data});
      });
  }
}

Mock API is a good mock backend for building frontend apps that needs to consume an API in the future. We store the API URL provided by Mock API as a class property so it can be accessed by different members of the class just as the componentDidMount lifecycle method is. Once there is a response and the promise resolves, we update the state using:

<pre class="ql-syntax" spellcheck="false">this.setState() </pre>

The add and remove methods now works with the API but also optimized for better user experience. We do not have to reload data when there is new todo, we just push to the existing array. Same with remove:

 // Add todo handler
  addTodo(val){
    // Assemble data
    const todo = {text: val}
    // Update data
    axios.post(this.apiUrl, todo)
       .then((res) => {
          this.state.data.push(res.data);
          this.setState({data: this.state.data});
       });
  }
  // Handle remove
  handleRemove(id){
    // Filter all todos except the one to be removed
    const remainder = this.state.data.filter((todo) => {
      if(todo.id !== id) return todo;
    });
    // Update state with filter
    axios.delete(this.apiUrl+'/'+id)
      .then((res) => {
        this.setState({data: remainder});      
      })
  }

Count and Style

We could keep track of the total items in our To-Do with the Title component. This one is easy, place a property on the Title component to store the count and pass down the computed count from TodoApp:

// Title
const Title = ({todoCount}) => {
  return (
    <div>
       <div>
          <h1>to-do ({todoCount})</h1>
       </div>
    </div>
  );
}
// Todo App
class TodoApp extends React.Component{
 //...
 render(){
    // Render JSX
    return (
      <div>
        <Title todoCount={this.state.data.length}/>
        <!--...-->
      </div>
    );
  }
  //...
 }

The app works as expected but not pretty enough for consumption. Bootstrap can take care of that. The following CodePen demo shows some updates made to change the look of the app:

See the Pen PzVyRm by Chris Nwamba (@christiannwamba) on CodePen.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

MongoDB - The Complete Developer’s Guide

Docker and Kubernetes: The Complete Guide

Fullstack Vue App with Node, Express and MongoDB

Building A REST API With MongoDB, Mongoose, And Node.js

Getting Started With MongoDB As A Docker Container Deployment

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Creating RESTful APIs with NodeJS and MongoDB Tutorial

Building REST API with Nodejs / MongoDB /Passport /JWT

Top 22 Tools for Faster Vue.js Application Development

Top 22 Tools for Faster Vue.js Application Development

Vue.js is another popular JavaScript framework that allows you to create single-page applications and user interfaces. It has a large and active open-source community who have created probably thousands of tools related to the framework.

So, here are some useful tools to help speed your development with Vue.js, save time, and deliver faster to production. Feel free to comment and add useful tools you work with to build faster :)

1.Official Vue.js Guide

This is the official Vue.js guide that helps you get started with the Vue framework. It includes a comprehensive learning guide, the Vue.js API documentation, official code style guide, code examples, and more. You can also get in touch with the Vue community by joining the forum, the chat or attending a meetup.

2.Storybook

StoryBook provides a rapid UI component development environment that enables you to explore a component library, navigate and view UI components in a real-time web development environment with hot-reload.

Through StoryBook you can develop components faster in isolation from your app, encouraging reusability. StoryBook can also be combined with Bit, to quickly prototype and develop components in different projects.

3.Vue loader and Vue-CLI

Vue-CLI

Vue CLI aims to be the standard tooling baseline for the Vue ecosystem. It ensures the various build tools work smoothly together with sensible defaults so you can focus on writing your app instead of spending days wrangling with configurations. At the same time, it still offers the flexibility to tweak the config of each tool without the need for ejecting.

Vue-loader

This is image title

Vue-loader is a loader for webpack that allows you to author Vue components in a format called Single-File Components (SFCs). The combination of webpack and vue-loader gives you a faster workflow for developing your Vue.js applications.

The project provides useful features such as using different webpack loaders for different parts of your components, treating static assets as module dependancies to be handled with webpack loaders, hot-reloading while preserving states during developments and more.

4.Nuxt.js

Nuxt.js is another Vue.js framework that lets you create performance-optimised user interfaces and single page applications. It makes server-side rendering of Vue.js applications possible. Improves the SEO of your web apps and results in more responsive UIs. Nuxt.js has a modular architecture, with 50+ modules you can choose from.

5.Vue Native

The Vue Native CLI is used to generate a Vue Native app, which is a React Native API wrapper. This means that with Vue Native, you can do anything that could be done with React Native.

6.Vue Electron Template

vue-electron takes advantage of webpack-4 with vue-loader, electron-builder, and some of the most used plugins like vue-router, vuex and so much more to provide an easy to use development and building enviroment.

7.Vue.js DevTools for Chrome

Vue.js DevTools for Chrome allows you to add a “Vue” tab to your Chrome DevTools. It’s a simple Chrome extension you can install with a single click. It’s based on the same GitHub project as the aforementioned Vue.js DevTools for Firefox. You can use it to inspect your Vue.js components, states, and events right in the browser.

8.Vue.js DevTools for Firefox

Vue.js DevTools for Firefox is a browser extension you can add to your Firefox DevTools. It extends your developer tools with an extra “Vue” tab that lets you analyze and debug your Vue.js applications. You can inspect your components, states, events, and more. You can have a look at the source code of the project on GitHub, too.

9.Vue.js Package for Atom

The Vue.js package for Atom adds Vue component support to the popular Atom source code editor. The package extends your editor with syntax highlighting and Vue.js code snippets.

You may also like: Keeping your Vue.js code Clean

10.Bit

This is image title

Bit helps you organize and share components between apps.

By sharing and reusing components your team can build apps faster. It also makes components easy to discover and choose from with visual features.

Bit’s workflow saves time and scales code-sharing for your team’s components, especially when working on multiple projects.

11.Vue.js Extension Pack for VS Code

The Vue.js Extension Pack is a collection of Vue-related extensions for the Visual Studio Code editor. It adds syntax highlighting, code formatting, and code snippets to your .vue files. It also includes additional developer packages such as ESLint, auto close tags, IntelliSense, and a few others.

12.Vuetify

Vuetify is a Vue.js component framework that follows Google’s Material Design guidelines. It provides you with 80+ semantic and reusable Vue components such as cards, carousels, buttons, icons, toolbars, and other design elements and it supports all modern web browsers even IE11 and Safari 9+ (with polyfills).

Vuetify comes with ready-made project scaffolding so that you can start building your Vue.js app with one single command.

13.Vue Design System

Vue Design System is an open source tool for building UI Design Systems with Vue.js. It provides you and your team a set of organized tools, patterns & practices that work as the foundation for your application development.

The tool is built on top of Vue.js, Vue Styleguidist, Vue Webpack Template & Theo and is aimed for designers and front-end developers who have at least basic knowledge of component based workflows + HTML, SCSS & JavaScript.

14.Vue Starter

Vue Starter is a Vue.js boilerplate for production-ready progressive web applications. It focuses on performance and development speed.

Vue Starter is an opinionated boilerplate using ton of optimisations and best practices. If you want to create a PWA using Vue.js, this is your go-to boilerplate.

15.BootstrapVue

BootstrapVue provides one of the most comprehensive implementations of Bootstrap V4 components and grid system available for Vue.js 2.5+, complete with extensive and automated WAI-ARIA accessibility markup.

16.Osiris

A Vue.js 2.0 universal responsive UI component library..

17.VueFace

VueFace is an open source component library for VueJS framework with around 40 components at the moment. It supports 20+ themes for giving different look & feel for all the components.

18.Vue Performance Devtool

Vue Performance Devtool is a browser extension for inspecting the performance of Vue Components. It statistically examines the performance of Vue components based on the measures which are collected by Vue using window.performance API.

19.Vue.JS WP Starter Theme

Vue.js WordPress Theme Starter helps you create your a WordPress theme using Vue.js on the front-end. It’s been based on the BlankSlate WordPress starter theme, and it has VueRouter and the Vuex state management pattern which you find in the project. The starter theme follows the development guidelines of Vue.js and comes with Firebase support.

20.Element

Element UI is a Vue.js 2.0 UI toolkits. It provides you with loads of customisable Vue components you can use to build a professional looking web application.

Element UI has a huge community, and it’s under active development with new commits being pushed every day. To get started quickly with Element UI, you can use the starter kit generated by Vue CLI.

21.Cube UI

Cube UI is a mobile UI component library created with Vue.js. The Components come with full unit tests and have been tested in production for over a year. Cube components look pretty similar to native mobile components with subtle animations and quick responses to user-generated events. You can customise the components according to your needs by editing the theme.styl file.

22.Vue templates and boilerplates

This is image title

Vue.js provides some great out-of-the-box templates to save time and help you start building your app using your favorite stack and setup. This is a great way to save time and speed your development without having to configure and boilerplate your application’s setup every time. Here are some of the best.

Webpack / webpack-simple

A full-featured Webpack + vue-loader setup built for vue-CLI with hot reload, linting, testing & css extraction. The simple version, which isn’t production oriented, provides a Webpack + vue-loader setup for quick prototyping.

Browserify / browserify-simple

A full-featured Browserify + vueify setup with hot-reload, linting & unit testing (also see: docs for vueify). Much like webpack-simple, the simpler version of this project is a simple Browserify + vueify setup for quick prototyping which is useful but not build for production-grade development.

Simple

This boilerplate is targeted at “beginners who want to start exploring Vue without the distraction of a complicated development environment”, and is basically the thinest version possible of a Vue setup in single HTML file.

Conclusion

Vue.js is great, powerful and all, but it still needs some help to enable developers to enjoy a less stressful life. This article has listed out 22 tools that will help every web developer in their pursuit of crafting amazing user interfaces and experience with Vue.

You may also like: Angular vs React vs Vue: Which one will be popular in 2020.

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