Categories
React Developers ReactJS

React Hooks with Typescript : UseCallback, UseMemo, UseContext And UseRef

Lets, check react advanced hooks, i.e. UseCallback, UseMemo, UseRef, and UseContext. All these come under React 16.8 version and help the user create an optimized react application.

Let’s create a react application environment for our project by using either of the following commands:   


1.yarn create react-app advanced-hooks-tutorial --template typescript
 # or 
2.npx create-react-app advanced-hooks-tutorial --template typescript

The above command will create a Project with the name “advanced-hooks-tutorial”. Once it’s done go to the directory and start the project either by “npm start” or “yarn start”.

We will be using yarn throughout this tutorial to maintain consistency.

Let’s now integrate the project with antd which is a design library by the name of antd design, that helps us to create some standard UI components. Additionally, you can use other design libraries as well if you want.

  1. Add antd to dependency
# terminal

yarn add antd

2. Add antd CSS to load stylings

# src/index.tsx

...
import 'antd/dist/antd.css';
...

That’s all for our project base, we have successfully integrated react hooks with antd design library.

UseCallback

UseCallback takes two arguments- In the first argument it takes an inline function that is called callback and in second arguments it takes an array of dependencies on which the callback function depends and returns a memoized callback.

The memoized callback changes only when one of its dependencies is changed. This is useful to optimize the child components that use the function reference from their parent component to prevent unnecessary rendering.

# syntax 

const memoizedCallback = useCallback(() => performSomething(param1, param2 ,...),[param1, param2, ...]);

Let’s see an example for this – Here, we are going to create an app consisting of two-buttons which will increment the age and salary of a person.

  • Create a file AdvancedHooksComponent.tsx in src/components directory- create the directory if not available there.
  • Now create a functional component, ie. AdvancedHooksComponent and import the component in App.tsx file.
# src/components/AdvancedHooksComponent.tsx

import React from 'react';

interface Props {
};

const AdvancedHooksComponent: React.FC<Props> = () => {

    return (
        <div>
            Advanced Hooks Component
        </div>
    );
};

export default AdvancedHooksComponent;

After this, your App.tsx file would look like :

# src/App.tsx

import React from 'react';
import './App.css';
import AdvancedHooksComponent from "./components/AdvancedHooksComponent";

const App: React.FC = () => {
  return (
    <div className="App">
        <AdvancedHooksComponent/>
    </div>
  );
};

export default App;

Now let’s add two child Button component named- AgeButton, SalaryButton, and a Title component. Import them in AdvancedHooksComponent.tsx.

# src/components/AdvancedHooksComponent.tsx

import React,{useState} from 'react'
import AgeButton from './AgeButton'
import SalaryButton from './SalaryButton'

interface Props {
};

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);
   
    const ageHandler = ()  => {
            setAge(age+1);
        };

    const salaryHandler = () => {
            setSalary(salary+500);
        };

    return (
        <div>
            <h1>Use CallBack Example</h1>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

We have used the useState hook to create state variables, i.e. age and salary and their corresponding dispatcher, ie. setAge and setSalary. Learn How to create State Variables.

AgeHandler and SalaryHandler are two inline functions that increment the age and salary on every click of AgeButton and SalaryButton respectively.

Note: If you don’t know how to use useState then you can refer our blog from here:- React Hooks With Typescript.

AgeButton component looks like :

# src/components/AgeButton.tsx

import React from "react";
import {Button} from "antd";

interface Props {
    clickHandler : () => void;
    age : number
}

const AgeButton = ({ clickHandler, age } : Props  ) => {
    console.log("Age Button Rendered Age = " + age)
    return (
        <Button onClick={clickHandler} type="primary" style={{ margin : 2}}>Increment Age</Button>
    )
};

export default React.memo(AgeButton);

SalaryButton component looks like :

# src.components/SalaryButton.tsx

import React from "react";
import {Button} from "antd";


interface Props {
    clickHandler : () => void;
    salary : number;
}

const SalaryButton = ({ clickHandler, salary } : Props ) => {
    console.log("Salary Button Rendered Salary = " + salary)
    return (
        <Button onClick={clickHandler} type="primary" style={{ margin : 2}}>Increment Salary</Button>
    )
};

export default React.memo(SalaryButton);

We have a console statement in both the AgeButton and SalaryButon that will help us in understanding the concept of useCallback hook later in the project.

Note: AgeButton and SalaryButton components are wrapped in the React.memo function which is a higher-order function. You can learn more about this from here:- React Memo.

Now start the app using the below command:

  yarn start

You will see the following output in the console:

Callback Example

As you can see in the web console, the rendering order of child component- first AgeButton component render and then SalaryButton component render.

Now, if we click on the increment Age Button then age will be incremented and react will re-render the component because if state changes then the component re-renders.

So the output looks like :

As you can see in the console- The AgeButton component re-render and age become 13, which is correct but the SalaryButton component also re-render and that is not necessary because we updated the age only and not salary.

So to fix this problem, useCallback comes into the picture:

We have to pass the ageHandler and salaryHandler function in the useCallback hook, so that memoized callback returns and changes only when passed dependencies changed.

For ageHandler- the only dependency is age and for salaryHandler- salary is the only dependency.

# src/components/AdvancedHooksComponent.tsx

import React, {useCallback, useState} from 'react';
import AgeButton from "./AgeButton";
import SalaryButton from "./SalaryButton";

interface Props {

}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);


    const ageHandler = useCallback(()  => {
        setAge(age+1);
    }, [age])


    const salaryHandler = useCallback( () => {
        setSalary(salary+500);
    }, [salary])


    return (
        <div>
            <h1>UseCallBack Example</h1>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

Now, if I click on the increment age button only the AgeButton component will re-render.


As you can see in the console only the AgeButton component is re-rendered. So this is how useCallback helps in preventing unnecessary rendering.

UseMemo

This hook will return a memoized value.

Suppose you have to compute a value that requires complex computation like fetching the list of 500 people from a database and then map over the list and then filter some person and finally update on the UI.

This operation is costly and recomputes after every rerender.

Using useMemo, we can simplify the process and this operation is performed only once and the value is stored in the cache. And the next time you want it, you’ll get it much faster.

# syntax

const memoizedValue = useMemo( () => costlyOperation(param1 , param2, ...) , [param1, param2, ...]);

The syntax of useMemo is similar to useCallback, but both work differently- useCallback returns a memoized callback(or function), on the other hand useMemo returns a memoized value (the result of the memoized callback).

Let’s see an example for this, where I made some modifications in AdvancedHooksComponent.tsx file :

# src/components/AdvancedHooksComponent.tsx

import React, {useCallback, useState} from 'react';
import AgeButton from "./AgeButton";
import SalaryButton from "./SalaryButton";

interface Props {
}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);


   const notMemoizedValue = () => {
        // some complex computation work here..
        let i = 0;
        while (i < 2000000000) i++;

        // after while break then do something here
        if(age % 2 === 0) return "Even";
        else return "Odd";
      }


    const ageHandler = useCallback(()  => {
        setAge(age+1);
    }, [age])


    const salaryHandler = useCallback( () => {
        setSalary(salary+500);
    }, [salary])


    return (
        <div>
            <h1>UseMemo Example</h1>
            <h3>{notMemoizedValue()}</h3>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

We have the “notMemoizedValue” function, which will check whether the current age is even or odd but we need some computational work to do before checking odd or even.

For simplicity, we will make a while loop that takes some time (which behave as complex computation like fetching data from database and so on). After the while loop breaks, the odd-even checking statement executes.

The result of “notMemoizedValue” function will be displayed on the UI.


So, as you can see our “notMemoizedvalue” function returns an even value but this value is not memoized value because if we press the increment salary button then the salary will be incremented. And after this rerendering occurs which leads to the recomputation of the “notMemoizedValue” function value that remains unchanged because age doesn’t change only the salary gets changed. Apart from this, you might feel some delay also.

So, Using useMemo we can return a memoized value of the “notMemoizedValue” function which saves the time from recomputation.

Using useMemo the code will look like :

# src/components/AdvancedHooksComponent.tsx


import React, {useCallback, useMemo, useState} from 'react';
import AgeButton from "./AgeButton";
import SalaryButton from "./SalaryButton";

interface Props {
}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);


    const memoizedValue =  useMemo( () => {
        // some complex computation work here..
        // for simplicity I wrote while loop here 
        let i = 0;
        while (i < 2000000000) i++;

        // after while break then do something here
        if(age % 2 === 0) return "Even";
        else return "Odd";

    } , [age])

    const ageHandler = useCallback(()  => {
        setAge(age+1);
    }, [age])


    const salaryHandler = useCallback( () => {
        setSalary(salary+500);
    }, [salary])


    return (
        <div>
            <h1>UseMemo Example</h1>
            <h3>{memoizedValue}</h3>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

Simply, remove the “notMemoizedValue” function with “memoizedValue” function and save the file.

Now, if you again press the increment salary button then the memoized value of Odd-Even will be return by the “memoizedValue” function and now this time you do not feel any delay.

UseRef

Using useRef Hook, we can access the DOM nodes or HTML elements as we access in vanilla javascript via “document” object, so that we can interact with those DOM nodes.

# syntax

const nameRef = useRef(initialValue);

useRef hook takes an initial value and returns a mutable object (a mutable object means the object whose state can be changed after it is created).

The return ref object holds a mutable value in its current property which will remain the same on every rerender.

Let’s do an example for this: In the same file AdvancedHooksComponent, let’s create an input element- :

# src/components/AdvancedHooksComponent.tsx

import React, { useEffect, useRef} from 'react';

interface Props {
}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {

        if(inputRef && inputRef.current) {
            inputRef.current.focus();
        }

    }, [])


    return (
        <div>
            <h1>UseRef Example</h1>
            <input type="text" ref={inputRef} style={{width : '40%'}}/>
        </div>
    );
};

export default AdvancedHooksComponent;

As you can see, we have an inputRef object containing initial value as null which gets passed in the input ref attribute.

Now, save the file and go to your browser- You will see that your input field is focused and you can do other things as well, as you do in vanilla javascript by “document” object.

fig

Note: useRef does not notify you when it’s content value changes. Also changing useRef current value doesn’t lead to re-render.

UseContext

To understand the concept of useContext hook– First we have to understand what is React Context API?

React Context API helps us to pass the data down to the child components (which depends on parent for data) from the root or parent component, instead of manually passing the data to every component by using props.

Let’s look at the below picture :

Suppose, we have three above components in our project and we want to pass the username of a user from AppComponent to UserComponent without using HomeComponent in between:-

App.tsx looks like :

# src/App.tsx

import React from 'react';
import './App.css';
import HomeComponent from "./components/HomeComponent";

export const UserContext = React.createContext('');

const App: React.FC = () => {
    
    const value : string = "Codersera";

  return (
    <div className="App">
        <UserContext.Provider value={value}>
            <HomeComponent/>
        </UserContext.Provider>
    </div>
  );
};

export default App

Here, we used React.createContext API to create a Context with an empty string as the initial value. It returns two components Provider and Consumer. Learn about API.

Provider: It is used to pass the data down to the child components.

Consumer: It is used to consume the data passed by the Provider component.

Note: If you don’t use useContext hook, then you can use the Consumer component. But here we use, useContext hook for consuming the data which makes the code less and more readable.

Provider component takes an attribute called “value” through which we can pass the data down. To use the passed data value, components should be wrapped inside the UserContext component.

# src/components/HomeComponent.tsx

import React from 'react';
import UserComponent from "./UserComponent";

const HomeComponent = () => {
    return (
        <UserComponent/>
    );
};

export default HomeComponent;

HomeComponent simply just renders UserComponent.

# src/components/UserComponent.tsx

import React, { useContext} from 'react';
import { UserContext } from '../App'


const UserComponent = () => {
    const username = useContext(UserContext);
    return (
        <div>
            <h1>UseContext</h1>
             <div>{username}</div>
        </div>
    );
};

export default UserComponent;

UserComponent uses the passed data value- First it imports the UserContext Object from App.tsx file, then passes this object in the argument of useContext hook (which returns the passed data value), as we have used inside the div tag.

The output of the above code looks like :


That’s it. We have successfully used useCallback, useMemo, useRef, and UseContext.

Categories
React Native Web ReactJS

React Native Web Vs React – A Comparison Guide For 2020

Often many of you are wondering isn’t React already existing for many years now and what is the point of the react-native web? Also, some people are thinking are both React native web and React the same thing?

Let’s check this comparison guide for 2020 for React native web and React and find out how “React-native for web” makes it possible to run React native components and APIs on the web using React DOM.

It is as simple as that. So, if you have an app and you want to build a web version of it, you should definitely learn React Native Web.

React Native Web Vs React

React web came before react native and much before react native for web.

Since react used virtual dom concept and there was a code conversion from jsx to html, developers thought of using the same concept for the apps, i.e. Write jsx and convert the code into java and objective c under the hood. And that’s how react native was born.

Also, developers thought of simplifying the code writing process by writing one code instead of two codebases. This way you have to write just one code and let it get converted into html, java, and objective c under the hood. And that’s how React native for web was born.

Is React Obsolete now or can React Native Web And React Together?


Although react native web is a great way to build your website, but I’d say use it only when you have plans to build both web and app versions together, or if you already have an app in react-native and are planning to launch the web version.

But, If you are looking to build only the website, then React is the way to go.

Advantages of React over React Native Web

  • React’s syntax is close to html. In React, we use div, h1, h2, p etc, and it is easier for a frontend engineer with html background to jump in. Whereas in react-native-web, we use <View>, <Text> which is what is used in reactnative, and is different than html way of coding.
  • You can easily fiddle with browser’s inspect element and change the html over there to test your changes in React, as the conversion of React code to the browser is relatively straightforward. Whereas in react native for web, the metro bundler auto-generates the classes, and it looks like the following:  You can’t really change the html directly for trial and error, you need to change the code in your editor itself.
react native web vs react

  • You can easily integrate thirdparty libraries. Most of the third-party libraries have react packages, even if they don’t you can easily integrate the library in the raw html and js form. Whereas with react-native-web integrating third-party libraries may not be that straightforward, although sometimes you can always create mocks.
  • React is more stable and you’d find a lot of documentation about almost everything on the web. Additionally, React has great community support.
  • React native for web is relatively new technology and you won’t find a lot of documentation for it. But it is picking up, so it’s a very good technology to learn.

Advantages of React Native Web over React

  • If you already have a codebase in react-native written, then with minimal changes you can run the same code on to the web. Whereas if you choose react, then you have to start almost from scratch. Although, you can save some time by setting a monorepo and keeping some utils code common between both the app and the web.
  • React native web is great if you want to build app and web versions together as it provides maximum code sharing, whereas with React you have to keep the view files separately.

As the community is driving towards using styledcomponents everywhere, slowly it is going to be quite similar development efforts to use react-native-web and react.


Now, Let’s have a look at the fundamentals of react-native-web:

Fundamentals of the React-Native Web:

Every frontend framework needs to have few things to make it usable.

  • Easy to start
  • Great development experience
  • Navigation
  • Styling
  • Good community support



Easy to Start

Setting up react native for web is quite easy with the expo. Since expo sdk version 33, expo gave the support of react-native web. Check out this detailed article for the react-native-web setup with expo.

Great Development Experience

With the expo kit, you get hot reloading and other great development benefits and experiences. Its been seen that changing styles sometimes get difficult with react-native-web when you are coming from html background and don’t’ have much experience with react-native.

Navigation

React-navigation is one of the most popular navigation library for react-native, and since version 3.0 it has extended the support for react-native for the web as well. Here is a great article if you are interested in integrating react-navigation with react-native-web.

Styling

Styling react-native-web component is exactly the same as styling react-native components. In case, you want to have specific styling for the web, you can always write the conditional styling using Platform.OS === ‘web’ check.

Good Community Support

Since react native web is a recent technology hence it doesn’t have a community as big as react. But you’ll for sure get a lot of help on the web. You can file issues on the official github repo https://github.com/necolas/react-native-web, ask questions over stackoverflow, reach out to us at codersera.com/contact. And If you are looking for a react-native-web developer to build your app and web all in one go, you can try our 7 days risk-free trial services.

Codersera risk free policy

Categories
React Developers ReactJS

React-Redux Hooks with Typescript in 2020

This is going to be a continued version of our previous blog, React Hooks with Typescript, So if you are new to hooks, I would suggest looking into that article first, which talks about setting up the starter kit of react hooks with typescript and AntD for UI components.

If you know basic of react hooks, like useEffect or useState, you can even give it a skip.

Since React push using of functional components, a lot of libraries around react start publishing their own hooks, Redux being one of them, as almost most react project use redux these days.

The Redux hooks APIs provide an alternative to connect HOC and go away with mapStateToProps, and mapDispatchToProps, and I must say these hooks API provide a much cleaner way of doing that.

Now without going much in theory, lets deep dive into the coding part.

create a new component file src/components/ReduxHooksComponent.tsx, if not already with 2 input fields and a submit button

Create a Normal Functional component


import React, {ChangeEvent, FormEvent, useState, useEffect} from "react";
import {Form, Input, Button} from "antd";

interface Props {
}

const ReduxHooksComponent: React.FC<Props> = () => {


    return (
        <Form layout="inline">
            <Form.Item>
                <Input type="text" placeholder="name"/>
                <Input type="text" placeholder="address" />
                <Button htmlType="submit" type="primary"> Submit </Button>
            </Form.Item>
        </Form>
    )
};

export default ReduxHooksComponent;

Now import this component in App.tsx


import React from 'react';
import './App.css';
import ReduxHooksComponent from "./components/ReduxHooksComponent";

const App: React.FC = () => {
  return (
    <div className="App">
      <ReduxHooksComponent/>
    </div>
  );
};

export default App;

Pretty Simple. Right! after running the code it should render a component with 2 input and a submit button.

Setting up the store, actions, and reducers.

Firstly add redux and react-redux to the project


yarn add react-redux @types/react-redux redux

Create two files, src/store/index.ts and src/store/root-reducer.ts

let’s start creating each and every component of root reducer, which would be actions, states, reducers

# src/store/root-reducer.ts

import {Action, Reducer} from "redux";

export interface InitialState {
    name: string;
    address: string;
}

export const initialState: InitialState = {
    name: '',
    address: '',
};

export interface DispatchAction extends Action {
    payload: Partial<InitialState>;
}

export const rootReducer: Reducer<InitialState, DispatchAction> = (state, action) => {
    return initialState;
};


Now we have a simple reducer that does nothing but returns the initial state.

Let’s create a store using this rootReducer, so our src/store/index.ts will look like


import {DispatchAction, InitialState, rootReducer} from "./root-reducer";
import {createStore} from "redux";


export const store = createStore<InitialState, DispatchAction, null, null>(rootReducer);

Also, updating the index.tsx file to wrap App with Provider ans provide the store to the provider.

# src/index.tsx

........
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
........

That’s all, well you won’t see any visible changes on the browser, but eventually, you have integrated a redux into your react code.

Now let’s create some actions. Update the root-reducer.ts so that it should look something like

# src/store/root-reducer.ts

.......
export interface DispatchAction extends Action<ActionType> {
    payload: Partial<InitialState>;
}

export enum ActionType {
    UpdateName,
    UpdateAddress,
    DeleteName,
    DeleteAddress,
}

export const rootReducer: Reducer<InitialState, DispatchAction> = (state = initialState, action) => {
    if (action.type === ActionType.UpdateName) {
        return {...state, name: action.payload.name || ''};
    } else if (action.type === ActionType.DeleteName) {
        return {...state, name: ''};
    } else if (action.type === ActionType.DeleteAddress) {
        return {...state, address: ''};
    } else if (action.type === ActionType.UpdateAddress) {
        return {...state, name: action.payload.name || ''};
    } else return state;
};

Pretty Simple, Yes! We have just returned an updated version of the state with new values as per the actions suggest.

Lets create a Dispatcher too in the same file

src/store/root-redux.ts

.......
export class RootDispatcher {
    
    private readonly dispatch: Dispatch<DispatchAction>;
    
    constructor(dispatch: Dispatch<DispatchAction>){
        this.dispatch = dispatch; 
    }
    updateName = (name: string) => this.dispatch({type: ActionType.UpdateName, payload: {name}});
    
    updateAddress = (address: string) => this.dispatch({type: ActionType.UpdateAddress, payload: {address}});
    
    deleteName = () => this.dispatch({type: ActionType.DeleteName, payload: {}});
    
    deleteAddress = () => this.dispatch({type: ActionType.DeleteAddress, payload: {}})
}
......

Well, now we are done with all the dispatchers, actions, store. basically our entire redux is setup. Now all we need to do is dispatch actions from components and use values from the store.

Using Dispatcher and Store in Components via Hooks

Redux hooks provide 2 main hooks, useSelector and useDispatch

useSelector give access to the entire store object, and we can select only what we are interested in

useDispatch give access to dispatch, which will be used to create the Dispatcher object of RootDispatcher and then dispatch events to update state.

Let’s create an interface of all the property we are interested in accessing from the store,


interface StateProps {
    name: string;
    address: string;
}

UseSelector to assign name and address state


    const {name, address} = useSelector<InitialState, StateProps>((state: InitialState) => {
        return {
            name: state.name,
            address: state.address
        }
    });

Now useDispatch to get a dispatch object and create a new instance of RootDispatcher


const dispatch = useDispatch();
const rootDispatcher = new RootDispatcher(dispatch);

After integrating both state and dispatcher from to the component our file will look something like

#src/components/ReduxHooksComponent.tsx

import React, {ChangeEvent, FormEvent, useState, useEffect} from "react";
import {Form, Input, Button} from "antd";
import {useDispatch, useSelector} from "react-redux";
import {InitialState, RootDispatcher} from "../store/root-reducer";

interface Props {
}

interface StateProps {
    name: string;
    address: string;
}

const ReduxHooksComponent: React.FC<Props> = () => {

    const {name, address} = useSelector<InitialState, StateProps>((state: InitialState) => {
        return {
            name: state.name,
            address: state.address
        }
    });

    const dispatch = useDispatch();
    const rootDispatcher = new RootDispatcher(dispatch);


    return (
        <Form layout="inline">
            <Form.Item>
                <Input type="text" placeholder="name" value={name}
                       onChange={(e: ChangeEvent<HTMLInputElement>) => {
                           rootDispatcher.updateName(e.target.value)}
                       }
                />
                <Input type="text" placeholder="address" value={address}
                       onChange={(e: ChangeEvent<HTMLInputElement>) =>{
                           rootDispatcher.updateAddress(e.target.value)}
                       }
                />
                <Button htmlType="submit" type="primary"> Submit </Button>
            </Form.Item>
        </Form>
    )
};

export default ReduxHooksComponent;

NOTE: The selector is approximately equivalent to the mapStateToProps argument to connect conceptually. The selector will be called with the entire Redux store state as its only argument. The selector will be run whenever the function component renders. useSelector() will also subscribe to the Redux store, and run your selector whenever an action is dispatched.

useSelector() uses strict === reference equality checks by default, not shallow equality, to use shallow Equality, we can use shallowEqual from react-redux

so our selector code would look something like


    const {name, address} = useSelector<InitialState, StateProps>((state: InitialState) => {
        return {
            name: state.name,
            address: state.address
        }
    }, shallowEqual);

Categories
React Developers React Native Developers React Native Web ReactJS

Running react-native-web using expo in 2020

Since expo sdk version 33, expo supports react-native-web.

In this blog, we’ll see how to set up your react-native-web project using expo.

Installing expo


// install expo-cli
npm i -g expo-cli

// create expo project
expo init

Install expo-cli if you don’t have it installed already, you can use nvm and yarn as well instead of npm.

After running expo init you’ll be presented with a few options to choose the starter kit from.

You can choose any one of those, but for this blog, we’ll use the first one, which is the blank project in javascript. Now, it will prompt you to enter the project name and the slug. Slug is the URL part that’s needed when you try to publish the app on the expo server.

cd into the project directory and run the expo start --web

If you want to quickly jump and see the code, check this GitHub repo [master branch]


cd rn-web
expo start --web

It should launch the webapp in your browser.

expo with react native web

Let’s make some changes in the App.js file and check if hot reloading works.


// App.js
export default function App() {
  return (
    <View style={styles.outer}>
      <Header/>
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app! let me do some change</Text>
      </View>
    </View>
  );
}

You should see the browser reflecting the changes automatically. If you’d like to see my hussle with react-native-web setup check this video.

Adding components to react-native-web

Let’s add a few components to our app now.
Create a Header.js file in components folder


// components/Header.js

import React from 'react';
import { StyleSheet, Text, View, Dimensions } from 'react-native';

const {width, height} = Dimensions.get('window');

function Header () {
        return (
            <View  style={styles.header}>
                <Text>I'm header</Text>
            </View>)
}
const styles = StyleSheet.create({
        header: {
               height: height/10,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'red',
        },
});
export default Header;

And include Header.js in your App.js file.


// App.js

import React from 'react';
import {Dimensions, StyleSheet, Text, View} from 'react-native';
import Header from './components/Header';
const {width, height} = Dimensions.get('window');

export default function App() {
  return (
    <View style={styles.outer}>
      <Header/>
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app! let me do some change</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({

  outer: {
    flex: 1,

  },
  container: {
    height: height*9/10,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

react-native-web

On the terminal, press i and it will launch the ios simulator or press a and it will launch android emulator, and you should see the app running in the mobile device as well.

react-native-web-expo

If you want to avoid using terminals, Expo also provides you with the browser UI interface which looks like this.

expo in browser

This is the beauty of react-native and react-native-web, you need to write the code once and can run it on multiple platforms. Like react-native-web there are other packages like react-native-windows which lets you run react native apps on the windows phone and PC.

Similarly, react-native-macos let’s your run the app on mac os.

In the next blog, we’ll integrate the navigation library into react-native-web as navigation is an important part of any frontend framework.

Categories
Programming React Developers ReactJS

React Hooks with Typescript: Use State and Use Effect in 2020.

In this blog, we are going to see how functional components can be used with react hooks to reduce the amount of code used in writing class-based components and still achieving all the features of it.

We are going to use typescript for this tutorial, so that our code remain 100% typesafe, and I must say if you are doing a big project, Typescript is a must feature one should go with, which helps to keep the code clean.


npx create-react-app codersera-hooks-tutorial --template typescript
  # or
yarn create react-app codersera-hooks-tutorial --template typescript

The above command will create a project with the name codersera-hooks-tutorial. Once it is done, go straight to the directory and either npm start or yarn start, will kickstart the project.

We will be using yarn throughout this tutorial to maintain consistency.

Let us now integrate antd ( a design library by the name of ant design), which we will be using to have some standard UI components. And, this does not have to do anything with hooks or react in general.

Integrating antd in react with hooks

  • Add antd to dependency

yarn add antd
  • Add antd css to load stylings
# src/index.tsx

....
import 'antd/dist/antd.css';
.....

That’s all, we now have a complete typescript setup off react with antd design library integrated.

Using State with hooks in React (React.useState)

Let us see how the state is used with hooks. For this, we are going to create a simple form component, that will show the value in the input field upon submitting the form.

  • Create a StateHooksComponent.tsx file inside src/components directory, create the directory if not already there.
  • Now create a function StateHooksComponent and import the component in App.tsx file.
#src/components/StateHooksComponent.tsx

import React from "react";
interface Props {
}

const StateHooksComponent: React.FC<Props> = ({}) => {

    return (
        <div>
            State Hooks component
        </div>
    )
}

export default StateHooksComponent;

After this, your App.tsx file would look like:


import React from 'react';
import './App.css';
import StateHooksComponent from './components/StateHooksComponent';

const App: React.FC = () => {
  return (
    <div className="App">
      <StateHooksComponent/>
    </div>
  );
}

export default App;

Now, let’s add a button, input field and output view in StateHooksComponents.


const [name, setName] = useState<string>('');

The useState will return 2 things, one is the state variable, and the other is the dispatcher to set this state. We can use any naming convention, but it’s obvious to use the following syntax :

[xxx, setXxx]

The handler is assigned with an arrow function. For instance, there are two handlers for handlingSubmit and handling onChangeEvent.


    const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
    };

    const onNameChange = (e: ChangeEvent<HTMLInputElement>) => {
        setName(e.target.value);
    };

After making the following edits, your component will look something like this:


import React, {ChangeEvent, FormEvent, useState} from "react";
import {Form, Input, Button} from "antd";

interface Props {
}

const StateHooksComponent: React.FC<Props> = ({}) => {

    const [name, setName] = useState<string>('');

    const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        console.log(name);
    };

    const onNameChange = (e: ChangeEvent<HTMLInputElement>) => {
        setName(e.target.value);
    };

    return (
        <Form layout="inline" onSubmit={handleSubmit}>
            <Form.Item>
                <Input type="text" placeholder="name" value={name} onChange={onNameChange} />
                <Button htmlType="submit" type="primary"> Submit </Button>
            </Form.Item>
        </Form>
    )
}

export default StateHooksComponent;

And here is the output that you should expect after typing some content in the box and clicking on submit button.

Using Effects/Lifecycle with Hooks (React.useEffect)

useEffect basically provides the features of componentWillUpdate, componentWillMount, componentWillUnMount all in one.


    useEffect(() => {
        console.log('Component mounted');
        return () => {
            console.log('Component will be unmount')
        }
    }, []); # notice the empty array here, this is optional

Now, the above code is an example of generic useEffect, notice the empty array above. There are 3 ways in which the useEffect can be used.

  • If the array is empty, the function will get executed once during the mounting of the component, and the return function will be executed during unmounting. For example, this can be used to initiate API calls to fetch data that needs to be shown on the UI.
  • If no array is provided, the function will be executed on before and after each render, this is used to record how many times rendering is taking place.
  • If there is any state variable inside the array, then the effects function is executed once on the mounting of the component, and then each time the state is changed, the function is called. A very useful example of this property is, suppose you want to show an autosuggest options, let’s say user is typing in an input field and based on the initial text you want to show him auto-suggested words/sentence, then you can use this property to fetch the data from backend each time the input value is changing.


.......
const [name, setName] = useState<string>('');
const [options, setOptions] = useState<Array<string>>([]);
useEffect(()=> {
	if(name){
		// fetch auto suggest options from backend, 
		setOptions(data);
	}
}, [name])
..........

Now each time user type any character in the input field, which is assigned to name, auto-suggest data will be fetched from the server and updated to options state, which can be used to show the auto-suggest options

Below is the code block to show how the use effect will be called :


import React, {ChangeEvent, FormEvent, useState, useEffect} from "react";
import {Form, Input, Button} from "antd";

interface Props {
}

const StateHooksComponent: React.FC<Props> = ({}) => {

    const [name, setName] = useState<string>('');
    const [address, setAddress] = useState<string>('');

    const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        console.log(name);
    };

    const onNameChange = (e: ChangeEvent<HTMLInputElement>) => {
        setName(e.target.value);
    };

    const onAddressChange = (e: ChangeEvent<HTMLInputElement>) => {
        setAddress(e.target.value);
    };

    useEffect(() => {
        console.log('Component mounted');
        return () => {
            console.log('Component will be unmount');
        }
    }, []);

    useEffect(() => {
        console.log(`Any state changed Name: ${name}, Address: ${address}`);
    });

    useEffect(() => {
        console.log(`Name changed: ${name}`);
    }, [name]);

    return (
        <Form layout="inline" onSubmit={handleSubmit}>
            <Form.Item>
                <Input type="text" placeholder="name" value={name} onChange={onNameChange}/>
                <Input type="text" placeholder="address" value={address} onChange={onAddressChange} />
                <Button htmlType="submit" type="primary"> Submit </Button>
            </Form.Item>
        </Form>
    )
};

export default StateHooksComponent;

NOTE: Never change the state of the variable in 2, and never change the state of the variable you are watching in case 3 inside effect function, otherwise use effects will create an endless loop.

The above code will produce the following output:

So, this is how you can use functional components instead of classbased components and still use all the features that you were able to do with the class lifecycle methods.

Part 2: How to use React-Redux with redux hooks in typescript.

Categories
ReactJS

Vuejs Vs Reactjs- Comparison Guide For 2020

Javascript has single-handedly captured the web applications domain by making intelligent use of its frameworks and libraries like ReacJs and VueJs. No doubt it is the most useful and popular framework of our times, especially known for providing higher performances and ease of learning.

In addition, both the frameworks are extensively employed for designing the User interfaces and also used for working with the root library. And they have certain similarities too in reactivity, presence of virtual DOM model and component-based structure.

VueJs Vs ReactJs

Hopefully, this comparison will make you select the best framework for your business challenges and requirements in accordance with your project requirements, the expertise of the developers, market trends and insights.

VueJs is simpler, it features a lot of concepts from Angular 1 and React. You can use it without any build system — just include it in the HTML file. React is bigger and a little more complex (e.g. in terms of setting up).

JavaScript is undoubtedly one of the most popular languages in the world, and ReactJs and VueJs are the most influential and useful frameworks of this era on whom all the major software developments companies are working. Let’s see this comparison guide to have better clarity in understanding their differences.

ReactJs Vs VueJs- quick comparison

Comparing Vue and React-VueJs Vs ReactJs

What Is React?

React is a library for creating reusable and attractive UI components. It is very suitable for components that require frequent data changes. In React, one can build reusable user interfaces by breaking them into smaller components in place of templates and HTML. It is one of the many Javascript MVC frameworks that are ruling today’s market.

Pros of ReactJs:

  • Flexibility and Responsiveness: It offers maximum flexibility and responsiveness.
  • Virtual DOM: As it is based on a document object model, it allows the browser-friendly arrangement of documents in HTML, XHTML, or XML format.
  • Rich JavaScript Library: Contributors from all over the world are putting in the effort to add even more features.
  • Scalability: React has been proven to be better for large-scale apps due to its flexible structure and scalability.
  • Constantly Evolving: React is backed by professional developers from Facebook who continuously look for ways to improve it. 
  • Web or Mobile Platform: React provides the React Native platform which can be used for developing native-rendered apps for iOS and Android through the same React component model.

Cons of ReactJs

Due to the complex setup process, properties, functions, and structure, it requires deep knowledge to build an application.

Companies Using ReactJs:

  • Facebook
  • Instagram
  • Netflix
  • New YorkTimes
  • Yahoo
  • WhatsApp
  • Codecademy
  • Dropbox
  • Airbnb
  • Asana
  • Microsoft

What is VueJs

VueJs is an open-source JavaScript framework capable of developing single-page applications. It is used as a web application framework with the aim of simplifying web development. VueJs application development has captured significant attention from developers across the globe in order to build amazing web apps. VueJs is a progressive framework for building eye-catching UIs for the web. It was released in 2014 by Evan You, a former Google developer who worked on AngularJS and decided to exclude difficulties of the Angular framework and build something lightweight.

There are many reasons for its popularity but one of the key reasons is its ability to re-render without any action. It allows you to build reusable, small, yet robust components which offer a composable framework that lets you add components whenever required.

Pros of Using VueJs

  • Ease-of-Use: Vue.js embraces standard HTML-based templates which make it easier to use and revamp an existing application.
  • Smoother Integration: Whether it is a single-page application or complex web interface, Vue.js offers smoother integration of smaller parts without any effect on the whole system.
  • Better Performance, Smaller Size: It takes up less space and tends to give better performance than other frameworks.
  • Well-written Documentation: It provides an easy learning curve through the detailed documentation and requires no extra knowledge; HTML and JavaScript will get the job done.
  • Adaptability: Overall sound design and architecture makes it a popular JavaScript framework. It provides hassle-free migration, simple and efficient structure, and reusable templates.

Cons of Using VueJs

VueJs framework has a small market share in comparison to Angular and React but it is rapidly getting popular because of its super useful features. Also, some issues do come up in terms of large-scale app development when using Vuejs.

VueJs has the potential to achieve milestones in web app development considering its modern features, speed, and flexibility.

In comparison to React, VueJs has fewer downloads and it is mainly popular for building attractive single-page applications and web applications. However, Vue.js features an adaptable architecture which makes it one of the widely used frameworks with up-to-date libraries and packages.

Companies Using Vue.js

  • Facebook
  • Netflix
  • Adobe
  • Grammarly
  • Behance
  • Xiaomi
  • Alibaba
  • Codeship
  • Gitlab
  • Laracasts

In-Depth Comparison of Both Frameworks

  • Rerendering and Optimization

When you compare React and Vue, speed can’t be a significant comparison factor in deciding which is better. In terms of performance, its re-rendering feature is a significant differentiator. React’s mechanism triggers the re-rendering of an entire component tree when the component’s state is changed. To avoid the unnecessary re-rendering of subcomponents, extra features and properties may be used.

Also, VueJs offers optimized re-rendering in which the system keeps track of dependencies during its render and works accordingly.

Rerendering of Vue is the most distinguishing feature which makes it a widely embraced framework by the developers across the world.

  • Routing and State Management Solutions

In component-based frameworks like React and Vue, you need to pay more attention to the state management and data flow as scaling begun during an application. This is because there are a number of components interacting with each other and sharing data.

In such a scenario, React offers an innovative solution called Flux/Redux architecture which represents unidirectional data flow and an alternative to the famous MVC architecture. Now, if we consider the Vue.js framework, there’s a more advanced architecture called Vuex which integrates into Vue and offers an unbeatable experience.

  • Building Tools

React and Vue both have a pretty good development environment. With little or no configuration one can create apps that get you up and running with the latest practices and templates.

Both of these bootstrap tools tend to give you a comfortable and flexible development environment and a superior starting point to get you started with coding.

When to Use VueJs Over ReactJs?

Vuejs is better than React when smaller, flexible and faster applications are required.

When there is a requirement for a lightweight, faster, and modern UI library for crafting a topnotch SPA (single-page application), one must use VueJs. This is beneficial for developers who are used to working with HTML. Also, it provides reusability of the components making web applications creation a magical experience for the developers.

When to Opt for ReactJs Over VueJs?

React Is Better Than Vue.js when there is no requirement to build mobile apps and there is a need to build large-scale applications. React is a light-weight and easy version migrating, having strong professional community support to solve any issue.

Final Words

Whether ReactJs or VueJs, both frameworks have no major differences and this decision is completely subjective based on the requirements of your projects. If you want to integrate a front-end JavaScript framework into an existing application, VueJs is a better choice and when there is a need to build mobile apps with JavaScript, ReactJs is definitely the way to go.

Vuejs and ReactJs are both great tools for building an interactive user interface. Because of its familiar templating syntax and use of components, integrating or migrating existing projects to Vue is faster and smoother.  Vue is great for startups but can be just as well be used in large-scale applications.

Cross-platform app development is already quite popular and both frameworks are in a race to provide the superior cross-platform app development experience. React’s React Native is a mature and widely used platform for native-rendered apps. On the other side, Vue’s Weex is still evolving and aims to provide a smooth development experience to create apps for iOS and Android.

Categories
Android ReactJS

Why Learning ReactJs Makes Sense In 2020?

ReactJS is a declarative, efficient JavaScript framework to build interactive user interfaces (UI) with greater ease and flexibility. It provides many advantages in designing simple views for different states in an application and greater ease in updating and rendering the right components efficiently just when the data changes.

Benefits Of React.js
Benefits Of React.js

React is providing the developer’s a better work experience and the advantage to change any component at any point in time without affecting the rest of the applications, resulting in widespread business support and innumerous websites built on React.


React JS is a very competent dynamic application for preparing larger web apps in a coordinated, flexible way where application UIs can be designed in a scalable and swift manner.

React's lifecycle
REACT’S LIFECYCLE METHODS

React is winning the hearts as a solid front-end development application due to its flexibility, better performance, and enhanced usability features to use the applications on both clients as well as the server-side.

Also, the’ Similar tech’ survey report suggests that the “United States of America” is the front-runner worldwide in hiring react developers for many future projects along with present ventures.

Let’s Check Few Advantages Of ReactJs Which Are Making It A Developer’s Favourite:

Suitable for Start-Ups As Well As Established Businesses

React provides hassle-free modification in existing functionalities allocating very little time and budget on the development process prompting major business brands to adopt the technology.

pros and  cons of react
pros and cons of react

Enhances Productivity

React is loaded with exceptional features creating better visual delight in terms of front-end designs as it eliminates the “Jquery” which is a code-heavy framework. Also, Virtual DOM increases the speed of web applications creating better productivity for that web application process.

VIRTUAL DOM IN REACT

Since many applications have complex logic and changes made in one component can affect others. So, developers at Facebook came up with a brilliant enhanced productivity feature in React by providing it with the ability to re-employ the same/ earlier used assets which makes workflow easier for the developers.

Re-use of assets is very common among developers, who typically re-employ the same digital objects for better productivity. One can start with the finest components (checkbox, button, etc.), then move on to wrapper components comprising of tiny elements and move forward to the main root component.

Code Stability

React JS ensures a more stable code by using downward data flow only so that the parent structure doesn’t get affected by any minutest of a change that occurs in the child structure.

In changing an object, developers only need to modify their state, make amendments for specific components. This kind of data binding structure ensures code stability and smooth application performance.

Additionally, it provides a fault-tolerant ‘UI’ because of the component creation aspect, which allows developers to efficiently conduct unit testing to avoid system crashes. Code reusability enables reducing time performing redundant tests to improve code quality giving stability to Code structure.

SEO friendly Platform

Top developers recommend learning ReactJS to budding young developers for better SEO experience which generates heavy traffic to your site and it is the guaranteed criteria for online success. ReactJs library is better-equipped in dealing with search engine failure, creating a great SEO friendly environment.

LEARN REACT FOR  BEST BUSINESS EXPERIENCE
DEVELOPER’S DELIGHT REACT IS THE BEST BET FOR A GREAT SEO EXPERIENCE

React reduces page load time through faster rendering and quickly adapts the performance in real-time according to user traffic demand, such type of features are not perfectly handled by other frameworks. This aspect of quick rendering is crucial for online success, as we know faster the speed more the number of users.

Simple to learn

ReactJS is very easy to learn and more focused than some other JavaScript framework. Many businesses are shifting or adopting React library because of the simplicity it provides and ease of use. Ease of Learning React is the best advantage as compared to other popular front-end frameworks like Angular and Vue.

When technology is difficult to learn, it gets difficult to complete a project on it and make it successful. So, enterprises prefer to deploy that technology which is easy to learn for the developing team and finish the project in scheduled time.

Better front-end Development Experience:

React Javascript library is growing its base among the developer’s community and so far thousands of websites have been built using React’s dynamic features of providing better features, great work-experience, and better web application development.

Its flexibility, better performance, and better usability features make it a very solid front-end development app

Conclusion:

Learning “ReactJS” is the need of the hour and makes sense as it is providing much-needed ease to developers in building highly engaging web applications and user interfaces in very lesser time, where they create large scale apps with frequently changing data. React’s benefits of being robust, advanced, responsive,non-risky, user-friendly far exceed its disadvantages and developers and organizations understand React’s relevance in the market, so they are promoting its learning and deployment wholeheartedly.

Word Of Advice:

The migration process from Reactjs can get rather tough and time-consuming at times so think about all such factors regarding time completion etc.before starting your Project on React.

Categories
Angular Development Frontend Developers Javascript Node React Developers ReactJS

23 JavaScript Interview Questions And Answers

JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, it is one of the three essential technologies of World Wide Web content production; the majority of websites employ it and it is supported by all modern web browsers without plug-ins or any kind of other extensions.

“Javascript is the duct tape of the Internet.”

Let’s starts with some common Qs about JavaScript.

  • JavaScript is developed by- Netscape Communications Corporation Mozilla Foundation, Ecma International.

  • It designed by- Brendan Eich

  • JavaScript is called- JS

  • The extension filename of JavaScript- .js

  • JavaScript Media type- application/javascript, text/javascript.

  • The current version of JavaScript- ECMAScript 2018.

In this guide, you’ll find example interview Qs and answers you can refer to when seeking a new JavaScript developer to make your dynamic user interfaces come to life. You’ll also get some practical Qs on how to use these Qs to reliably identify results.

Q 1. Is JavaScript and JScript the same?


Answer. Both JavaScript vs JScript is designed to make dynamic web pages and interactive content.

  • Javascript is a scripting language (supports scripts) for Web pages but it is also used in non-browser environments as well. It is a powerful, lightweight, interpreted, scripting language with first-class functions (i.e. the language supports passing functions as arguments to other functions).
  • JScript is also a scripting language, much similar to JavaScript. It is a dialect of the popular ECMAScript standard reverse-engineered by Microsoft. JScript is subsidy by Microsoft and used in one of the most popular web browsers Microsoft’s Internet Explorer. JScript can also be called “Microsoft’s JavaScript”.
DifferenceJavaScriptJscript
TypeScripting languageScripting language owned by Microsoft.
SimplicityIt needs to write scripts manually. Same as JavaScript in this context.
Browser
Compatibility
It needs to handle multiple
browsers compatibility.
Only support by Microsoft’s internet
explorer.
Active Content
Creation
Does not support active content
creation.
With JScript, you can create active
online content for WWW.
Object
Access
JavaScript cannot access web browser
objects.
JScript can easily access-
objects exposed by internet explorer.

Q 2. Justify the use of let and const in JavaScript?


Answer. Earlier in javascript, developers use the var keyword for creating variables. let & const keyword is introduced in version ES6 with the vision of creating two different types of variables in javascript one is immutable and the other is mutable. The use if let and const in JavaScript:

  • let

let is used for variable declaration as it comes as an improvement to the var declarations. let is a block code bounded as {}. So a variable declared in a block with the let is only available for use within that block.

  • Example:
let greeting = "say Hi";
   let times = 4;

   if (times > 3) {
        let hello = "say Hello instead";
        console.log(hello);//"say Hello instead"
    }
   console.log(hello) // hello is not defined
  • const

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.

Like let declarations, const declarations can only be accessed within the block it was declared in.

const cannot be updated or re-declared

This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const.

  • Example:
const greeting = "say Hi";
    greeting = "say Hello instead";//error : Assignment to constant variable. 

Q 3. Explain the MUL function in JavaScript?


Answer. MUL means a simple multiplication of numbers. It is a technique in which you pass one value as an argument in a function and that function returns another function to which you pass the second value and the process goes on. Multiplies two expressions. This is the functional equivalent of the (*) operator.

Q 4. List the Frameworks and Data types supported by JavaScript?


Answer. The frameworks used by JavaScript are:

  • Node.js
  • Angular.js
  • React
  • Vue.js
  • Ember.js
  • Meteor
  • Backbone.js

Data types supported by JavaScript are:

  • Symbol
  • String
  • Boolean
  • Null
  • Undefined
  • Number
  • Object

Q 5. How you can redirect a page to another page in JavaScript?


Answer. There are several ways to redirect the page to another page in JavaScript. These are:

  • Using location.href: It is the first approach to redirect page. In this, we can go back to access the original document.

  • Using location.replace: Another approach to redirect page. In this, it is not possible to navigate back to the original document by clicking on the back button as it removes the URL of the original document. 

Q 6. Clarify some design patterns in JavaScript?


Answer. The design pattern is a reusable solution to a commonly occurring problem in software design. Some of the design patterns are:

  1. Behavioral Patterns: 
    These patterns are to improve communication between objects and to recognize patterns. Visitor, states, strategy, Memento, Mediator, Iterator, Command, Chain of responsibility and observer are examples of Behavioral patterns.

  2. Creational design pattern: 
    These patterns deal with the mechanism of object creation which optimizes object creation with the basic approach. Factory method, Abstract Factory, Builder, Prototype, and Singleton are the categories of Creational design pattern.

  3. Concurrency design patterns: 
    These patterns handle with multi-thread programming paradigms. Some popular categories of concurrency design patterns are Scheduler, Nuclear reaction, and Active object.

  4. Structural design pattern: 
    These patterns deal with different classes and objects to provide new functionality. Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and proxy are the categories od structural design patterns.

  5. Architectural design patterns: 
    These patterns used to deal with architectural designs. Like: MVC (Model-View-Controller), MVVM (Model-View-ViewModel), and MVP (Model-View-presenter).

Q 7. Explain promise in JavaScript?


Answer. A Promise is a proxy for a value not necessarily known when the promise is created. It allows the developers to associate handlers with asynchronous action’s eventual success value or failure reason. Essentially, a promise is a returned object that you can attach callbacks to, instead of passing callbacks into a function.

  • 3 states to a promise:
  1. pending: awaiting promise response.
  2. resolve : promise has successfully returned.
  3. reject: failure occurred.
  • Syntax:
new Promise(executor);
Function process of promise

Q 8. What are the advantages of using JavaScript?


Answer. Some key advantages of JavaScript are:

  • JavaScript is an easy language to learn.

  • It is comparatively fast for the end-user.

  • Easy to debug and test.

  • JavaScript is platform-independent.

  • It works on the client6-side.

  • Also, has powerful frameworks.

  • Event-based programming language.

  • Procedural programming capabilities.

Q 9. How to get inner HTML of an element in JavaScript?


Answer. InnerHTML property of HTML DOM is used to get inner Html of an element in JavaScript.

  • Example:
<script type="text/javascript">
	var  inner= document.getElementById("inner").innerHTML ;
	console.log(inner); // This is inner Element
	document.getElementById("inner").innerHTML = "Html changed!";
	var  inner= document.getElementById("inner").innerHTML ;
	console.log(inner); // Html changed!
</script>

Q 10. What are the Arrow functions in JavaScript?


Answer. Arrow functions were introduced in ES6. Arrow functions allow the developers to write shorter function syntax.

hello = () => {
  return "Hello World!";
}

An arrow function expressions is a syntactically compact alternative to a regular function expression, but this function has its own bindings to the arguments, super, this, and new.target keywords.

Q 11. How to encode and decode a URL in JavaScript?


Answer. Encode and Decode a URL in JavaScript:

  • encodeURI() function is used to encode an URL in Javascript.It takes a url string as parameter and return encoded string. Note: encodeURI() did not encode characters like / ? : @ & = + $ #, if you have to encode these characters too please use encodeURIComponent().

    Usage:
var uri = "my profile.php?name=alex&occupation=danciNG";
var encoded_uri = encodeURI(uri);
  • decodeURI() function is used to decode a URL in Javascript. It takes an encoded URL string as a parameter and returns decoded string.

    Usage:
var uri = "my profile.php?name=alex&occupation=danciNG";
var encoded_uri = encodeURI(uri);
decodeURI(encoded_uri);

Q 12. Classify the different ways of empty an array in javascript?


Answer. In Javascript, there are many ways to empty an array, here are the four major ways to empty an array:

  • By poping the elements of the array.
var arr2 =[1,4,5,6];
while(arr.length > 0) {
    arr.pop();
}
  • Assigning array length to 0.
var arr2 =[1,4,5,6];
arr2.length=0;
  • Using .splice().
var arr =[1,4,5,6];
arr.splice(0,arr.length)
  • By assigning an empty array.
var arr1 =[1,4,5,6];
arr1=[];

Q 13. How to remove duplicates from JavaScript Array?


Answer. The three main approaches to remove duplicates from JavaScript Array:

  • By using Set:

It is the simplest way to remove duplicates because Set is an inbuilt object to store unique values in an array.

How to use set:

 function uniquearray(array) { 
       let unique_array= Array.from(set(array)) 
       return unique_array;}

By this code, you can easily create a set of an array that automatically eliminates duplicate values in JavaScript.

  • By using Filter:

This is another way to remove duplicates from an array. In the Filter method, it requires three arguments: Current element, Index of the current element, and Array.

How to use Filter:

function unque_array (arr){
 let unique_array = arr.filter(function(elem, index, self) {
 return index == self.indexOf(elem); } 
return unique_array }
 console.log(unique_array(array_with_duplicates));
  • By using for loop:

This is also a way to remove duplicates, but in this developer make an empty array in which those elements will be added from the duplicate array to get the unique elements.

Code use as:

Array dups_names = ['Tom', 'Pal', 'Fred', 'Rongo', 'Ron'];
function dups_array(dups_names) {
 let unique = {};
 names.forEach(function(i) {
    If (!unique[i]) {
      unique[i] = true;    }
  });
return Object.keys(unique);}   // Tom, Pal, Fred, Rongo
Dups_array(names);

Q 14. Are the results of 6 + 4 + ‘45’ and 6 + 4 + 45 the same?


Answer. No, the results should be different from each other because the results for the two statements are very different from each other. 6 + 4 + 45 gives the result 55, which is the expected answer for the addition of numbers. But, 6 + 4 + ‘45’ returns 1045 as a result. This is because 45 is a string and 6 and 4 are numbers. The presence of the string specifies that the + operator is a string operator for concatenation rather than an arithmetic operator.

Q 15. What is null, undefined, and undeclared JavaScript variable?


Answer.

  • Null

It can be assigned to a variable to represent no value. It is an assignment value.

var b = null;
console.log(b); //null
console.log(typeof b); //object
  • Undefined

It means a variable has been declared but has not yet been assigned a value

var a;
console.log(a); //undefined
console.log(typeof a); // undefined
  • Undeclared

If a variable is not declared then the browser throws an error.

console.log(nonDeclaredVariable);
 
// Uncaught ReferenceError: nonDeclaredVariable is not defined
//    at <anonymous>:1:13
 
console.log(typeof nonDeclaredVariable); //undefined

Q 16. What is the purpose of ‘This’ operator in JavaScript?


Answer. The JavaScript this keyword refers to the object it belongs to. This has different values depending on where it is used. In a method, this refers to the owner object and in a function, this refers to the global object.

Q17. Explain the terms synchronous and asynchronous code.


Answer. The synchronous code is something that should be finished before anything else can happen, or in other words, the synchronous code is blocking. And the Asynchronous code is something in which actions can happen and is not dependent on other actions- in other words, it is non-blocking.

Q 18. Are “==” and “===” operators different in JavaScript?


Answer. “==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two variables are different. So, the second option needs both the value and the type to be the same for the operands.

Q 19. How to Calculating the Fibonacci series in JavaScript?


Answer. Fibonacci Series is a sequence of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two.

function fibonacci(n) {
let arr= new Array(n+1);
arr[1]=1;
arr[2]=1;
for(let i=3;i<=n;i++)
{
 arr[i]=arr[i-1]+arr[i-2];
}
for(let i=1;i<=n;i++)
{
 console.log(arr[i]);
}
return;
} 


Answer. The process of Create, Read, and Delete a cookie by using JavaScript:

  • Cookie creating process-

The simple way to create a cookie is to assign a string value to the document.cookie object.

Syntax:

document.cookie = "key1 = value1; key2 = value2; expires = date";
  • Reading a cookie-

It is just as simple as writing one for the developers because of the value document.cookie object is the cookie. So you can use this string whenever you want to access it.

This fulfills your two conditions:

  1. The document.cookie string will keep a list of anme= value pairs separated by semicolons.

  2. It is easy for the developers to use the string’s split() function to break the string into key and values.
  • Delete a cookie-

If you want to delete a cookie, that subsequent attempts to read the cookie return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.

Q 21. Consider the following code:

function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 2;
}
}
test();

What is the result of executing this code and why?

Answer. The result of this code is undefined and 2.

The reason is that both variables and functions are hoisted but variables don’t retain any assigned value. So, at the time the variable “a” is printed, it exists in the function but it’s still undefined. Stated in other words, the code above is equivalent to the following:

function test() {
var a;
function foo() {
return 2;
}
console.log(a);
console.log(foo());
a = 1;
}
test();

Q 22. List the comparison operators supported by JavaScript?


Answer. The comparison operators are:

  • < Less than
  • > Greater than
  • <= less than or equal to
  • >= Greater than or equal to
  • == Equal to
  • != Not Equal to
  • === Equal to with datatype check
  • !== Not equal to with datatype check

Q 23. How you can clone an object in JavaScript?


Answer. Object.assign() method is used for cloning an object in Javascript.

Syntax:

 var x = {myProp: "value"};
 var y = Object.assign({}, x); 

Categories
Development Frontend Developers React Developers React Native Developers React Native Web ReactJS Top Coder

How To Make React VR Apps

VR web apps can be built with the React VR apps. WebVR is an experimental API enabling the creation and viewing of VR experiences in your browser. This new technology enables you to grant access to virtual reality regardless of the devices at hand.

The only thing you need to make a React VR app is a headset and a compatible browser. If you are just viewing a web VR application then you don’t need even for a headset. React VR is a great framework to build VR websites or apps on JavaScript. It utilizes the same design as React Native and lets you make virtual reality tours and under interfaces with the provided components.

Complete Example

is a headset and a compatible browser. If you are just viewing a web VR application then you don’t need even for a headset. React VR is a great framework to build VR websites or apps on JavaScript. It utilizes the same design as React Native and lets you make virtual reality tours and under interfaces with the provided components.

Technical Requirements


Before getting started with React VR, You required a proper setup for the dependencies that will be used to build and manage a React VR app. These are Node.js and the React VR CLI.

You need to install Node.js, ensure that the latest version is used. If not, do the following:

  • MacOS: Install Node.js using Homebrew
  • Windows: Install it from the nodejs.org
  • Linux: Use sudo apt-get install nodejs command

Then you have to install the React VR CLI using npm:

npm install -g react-vr-cli.

Getting Started


Navigate to the directory where you wish to create a new project and run the react-vr init MyFirstReactVR command.

Change the directory name to something like MyFirstReactVR and run npm start .

Click and try to drag your cursor around. Also, in browsers that support WebVR, you’ll be able to explore this VR environment with a headset in full virtual reality mode.

VR Tour Sample Using React VR


Now let’s make a VR tour with a few scenes and navigations in them. First of all, you need to prepare the architecture. In this example, we will make buttons within each scene for navigations and declare this in the constructor of a React component named index.js.vr:

constructor(props) {
    super(props);
    scenes: [{
        scene_image: 'initial.jpg',
        step: 1,
        navigations: [{
            step: 2,
            translate: [0.73, -0.15, 0.66],
            rotation: [0, 36, 0]
        }]
    }, {
        scene_image: 'step1.jpg',
        step: 2,
        navigations: [{
            step: 3,
            translate: [-0.43, -0.01, 0.9],
            rotation: [0, 140, 0]
        }]
    }, {
        scene_image: 'step2.jpg',
        step: 3,
        navigations: [{
            step: 4,
            translate: [-0.4, 0.05, -0.9],
            rotation: [0, 0, 0]
        }]
    }, {
        scene_image: 'step3.jpg',
        step: 4,
        navigations: [{
            step: 5,
            translate: [-0.55, -0.03, -0.8],
            rotation: [0, 32, 0]
        }]
    }, {
        scene_image: 'step4.jpg',
        step: 5,
        navigations: [{
            step: 1,
            translate: [0.2, -0.03, -1],
            rotation: [0, 20, 0]
        }]
    }]
}

Also, declare current_scene in the state in the constructor:

constructor(props) {
        this.state = {
            ...
            current_scene: {}
                ...
        }

For rendering, change the render() method, as seen below:

render() {
    return ( < View >
        < Pano source = {
            asset(this.state.current_scene['scene_image'])
        }
        style = {
            {
                transform: [{
                    translate: [0, 0, 0]
                }]
            }
        }
        /> {
            this.state.current_scene['navigations'].map(function(item, i) {
                return <Mesh key = {
                    i
                }
                style = {
                        {
                            layoutOrigin: [0.5, 0.5],
                            transform: [{
                                translate: item['translate']
                            }, {
                                rotateX: item['rotation'][0]
                            }, {
                                rotateY: item['rotation'][1]
                            }, {
                                rotateZ: item['rotation'][2]
                            }]
                        }
                    } >
                    < VrButton
                style = {
                        {
                            width: 0.15,
                            height: 0.15,
                            borderRadius: 50,
                            backgroundColor: 'blue'
                        }
                    } >
                    < /VrButton> < /Mesh>
            })
        } < /View>
    )
}

The last step to make this work is to set the current_scene state to the first element of the scenes array componentWillMount function:

componentWillMount() {
    this.setState({
        current_scene: this.state.scenes[0]
    });
}

The result should be like this on screen:

Now add a simple animation for the button and implement the logic to navigate between scenes. First of all, for navigation, you need to subscribe to the onInput event for our Mesh element, bind this function to this in constructor, and implement it:

...
constructor(props) {
    ...
    this.onNavigationClick = this.onNavigationClick.bind(this);
    ...
}
...
onNavigationClick(item, e) {
        if (e.nativeEvent.inputEvent.eventType === "mousedown" && e.nativeEvent.inputEvent.button === 0) {
            var new_scene = this.state.scenes.find(i => i['step'] === item.step);
            this.setState({
                current_scene: new_scene
            });
        }
    }
    ...
render() {
    var that = this;
    ... < Mesh key = {
            i
        }
        ...
    onInput = {
            e => that.onNavigationClick(item, e)
        }
        .... >
        ...
}

Then added a simple animation try it out. For this, you have added one more button inside the existing one in the render method and changed the size of it. Use native JS requestAnimationFrame function:

const DEFAULT_ANIMATION_BUTTON_RADIUS = 50;
const DEFAULT_ANIMATION_BUTTON_SIZE = 0.05;
constructor(props) {
        ...
        this.state = {
                ...
                animationWidth: DEFAULT_ANIMATION_BUTTON_SIZE,
                    animationRadius: DEFAULT_ANIMATION_BUTTON_RADIUS
                    ...
            }
            ...
        this.animatePointer = this.animatePointer.bind(this);
    }
    ...
componentWillUnmount() {
    if (this.frameHandle) {
        cancelAnimationFrame(this.frameHandle);
        this.frameHandle = null;
    }
}
componentDidMount() {
    this.animatePointer();
}
animatePointer() {
        var delta = this.state.animationWidth + 0.002;
        var radius = this.state.animationRadius + 10;
        if (delta >= 0.13) {
            delta = DEFAULT_ANIMATION_BUTTON_SIZE;
            radius = DEFAULT_ANIMATION_BUTTON_RADIUS;
        }
        this.setState({
            animationWidth: delta,
            animationRadius: radius
        })
        this.frameHandle = requestAnimationFrame(this.animatePointer);
    }
    ...
render() {
    ... < VrButton
    style = {
            {
                width: 0.15,
                height: 0.15,
                borderRadius: 50,
                justifyContent: 'center',
                alignItems: 'center',
                borderStyle: 'solid',
                borderColor: '#FFFFFF80',
                borderWidth: 0.01
            }
        } >
        < VrButton
    style = {
            {
                width: that.state.animationWidth,
                height: that.state.animationWidth,
                borderRadius: that.state.animationRadius,
                backgroundColor: '#FFFFFFD9'
            }
        } >
        < /VrButton> < /VrButton>
        ...
}

Now let’s implement manipulations with the animated button and its rotation. It will rotate the button on an X-Y-Z axis. To do so, you need to subscribe to the onInput event for the Pano component and change the rotation via arrow-up, arrow-right, and arrow-down buttons.

The last thing is to implement messaging of the VR thread and Main thread to exchange data. Below is the subscription code on receiving messages and posting a message when a scene changes or an image starts/ends loading.

componentWillMount() {
      window.addEventListener('message', this.onMainWindowMessage);
      ...
  }
  onMainWindowMessage(e) {
      switch (e.data.type) {
          case 'newCoordinates':
              var scene_navigation = this.state.current_scene.navigations[0];
              this.state.current_scene.navigations[0]['translate'] = [e.data.coordinates.x, e.data.coordinates.y, e.data.coordinates.z]
              this.forceUpdate();
              break;
          default:
              return;
      }
  }
  onNavigationClick(item, e) {
      ...
      postMessage({
          type: "sceneChanged"
      })
      this.state.animationWidth = DEFAULT_ANIMATION_BUTTON_SIZE;
      this.state.animationRadius = DEFAULT_ANIMATION_BUTTON_RADIUS;
      this.animatePointer();
      ...
  }
  sceneOnLoad() {
      postMessage({
          type: "sceneLoadStart"
      })
  }
  sceneOnLoadEnd() {
      postMessage({
          type: "sceneLoadEnd"
      })
  }
  render() {
      ... < Pano...
      onLoad = {
          this.sceneOnLoad
      }
      onLoadEnd = {
              this.sceneOnLoadEnd
          }
          ... / >
  }

In client.js, implement a zoom with the mouse wheel and a position change with a double-click. you need to store the VR instance and VRcamera instance to implement the logic above.

function init(bundle, parent, options) {
    const vr = new VRInstance(bundle, 'TMExample', parent, {
        // Add custom options here
        ...options,
    });
    vr.render = function() {
        // Any custom behavior you want to perform on each frame goes here
    };
    // Begin the animation loop
    vr.start();
    window.playerCamera = vr.player._camera;
    window.vr = vr;
    return vr;

Then subscribe to ondblclick and onmousewheel and implement the zoom and change position logic.

function onRendererDoubleClick() {
      var x = 2 * (event.x / window.innerWidth) - 1;
      var y = 1 - 2 * (event.y / window.innerHeight);
      var coordinates = get3DPoint(window.playerCamera, x, y);
      vr.rootView.context.worker.postMessage({
          type: "newCoordinates",
          coordinates: coordinates
      });
  }
  function onRendererMouseWheel() {
      if (event.deltaY > 0) {
          if (window.playerCamera.zoom > 1) {
              window.playerCamera.zoom -= 0.1;
              window.playerCamera.updateProjectionMatrix();
          }
      } else {
          if (window.playerCamera.zoom < 3) {
              window.playerCamera.zoom += 0.1;
              window.playerCamera.updateProjectionMatrix();
          }
      }
  }

get3DPoint is your custom function to transform screen coordinates to world coordinates using Three.js, implemented in cameraHelper.js.

import * as THREE from 'three';
export function get3DPoint(camera, x, y) {
    var mousePosition = new THREE.Vector3(x, y, 0.5);
    mousePosition.unproject(camera);
    var dir = mousePosition.sub(camera.position).normalize();
    return dir;
}

Sometimes, loading scene images takes time. thus, you have implemented the loader to show this process. In index.html, add a loader and CSS based on this w3cschool example.

<style>
    body { margin: 0; }
    #loader {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 1;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border: 16px solid #f3f3f3;
    border-radius: 50%;
    border-top: 16px solid #3498db;
    width: 120px;
    height: 120px;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
    }
    @-webkit-keyframes spin {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
    }
    @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
    }
    .animate-bottom {
    position: relative;
    -webkit-animation-name: animatebottom;
    -webkit-animation-duration: 1s;
    animation-name: animatebottom;
    animation-duration: 1s
    }
    @-webkit-keyframes animatebottom {
    from { bottom:-100px; opacity:0 }
    to { bottom:0px; opacity:1 }
    }
    @keyframes animatebottom {
    from{ bottom:-100px; opacity:0 }
    to{ bottom:0; opacity:1 }
    }
    #myDiv {
    display: none;
    text-align: center;
    }
</style>
<body>
    <div id='content' style="width:100%; height:100%">
        <div id="loader"></div>
    </div>
    <script src="./client.bundle?platform=vr"></script>
    <script>
        ReactVR.init('../index.vr.bundle?platform=vr&dev=true', document.getElementById('content'));
    </script>
</body>

And don’t forget message in client.js from the VR thread to enable/disable animation:

function init(bundle, parent, options) {
    ...
    vr.rootView.context.worker.addEventListener('message', onVRMessage);
    ...
  }
  function onVRMessage(e) {
    switch (e.data.type) {
      case 'sceneChanged':
      if (window.playerCamera.zoom != 1) {
        window.playerCamera.zoom = 1;
        window.playerCamera.updateProjectionMatrix();
      }
      break;
      case 'sceneLoadStart':
        document.getElementById('loader').style.display = 'block';
      break;
      case 'sceneLoadEnd':
        document.getElementById('loader').style.display = 'none';
      break;
      default:
      return;
    }
  }

Check your index.html or client.js.

Get The Complete Github Code Here

Categories
Development Frontend Developers Javascript Node ReactJS Startup Top Coder

Nuxt, Next, Nest! Confused?

Programming is the method to innovate something new and amazing. Being a coder, it is important to be aware of every new upcoming technology. “Nuxt”, “Next”, “Nest” a little confusing, right? They might sound similar but their practical application is different from each other.

The coders who aren’t familiar with these frameworks might get confused in the beginning, these are the perplexed and complex words. I’m going to explain all the concepts of Nuxt, Next, and Nest so stay tuned with me, in this article you may explore the uses and the installation of these frameworks. Surely, this article will help you to know about these frameworks in depth.

Do you ever think why do we actually need a framework? What are the uses of the framework?

  • A framework is a platform that provides a foundation on which software developers can create programs. It allows the coder to make robust applications.

  • Also, the framework provides diversified support for developing robust applications with pace and ease because it provides a standard way to build and deploy applications.

Before starting with these frameworks, let’s have a short briefing of CSR (client-side rendering) vs SSR (Server-side Rendering).

  • By these platforms, it is important to understand that Vue and React are the client-side Rendered (CSR) framework, which makes the page interactable and viewable.

WORKING OF CSR

📤 Server sending the response to the browser 📤

📥 Browser downloads JavaScript 📥

💬 Browser executes React 💬

🌐 The page now viewable and interactable 🌐

  • Using these platforms, Server-side Rendered (SSR) use to make the page interactable.

WORKING OF SSR

👩‍💻 Server sending ready to be rendered
HTML response to the browser
👩‍💻

📥 The browser renders the page, Now viewable
and browser downloads JavaScript
📥

🆗 Browser executes React 🆗

🌐 Page now Interactable 🌐

The first thing that needs to be clear is these three frameworks- Nust, Next, and Nest are different from each other but comes in Javascript Ecosystem.


If you’re a Vue.js programmer, then you probably heard of Nuxt.js. or if you’re not then let starts with Nuxt!

What is Nuxt.js?


Nust.js is a high-level framework that builds on Vue. It is an open-source application framework that is free and based on Vue.js, also Node.js, Webpack, and Babel.js. Nust comes under universal application which uses “meta-framework” as well as develops single page Vue apps.

The main aim to build applications with Nuxt.js that it is more flexible while creating any project because Nuxt helps the developers to create complex, fast, and universal web applications quickly.

What is Vue.js?

It is an open-source Javascript framework, it is faster as well as smoother to build user interfaces and single-page applications. The reason behind this is, Vue had familiar templating syntax and use of components, integrating or migrating the project make it more understanding by the beginners. For this reason, Vue is the best framework for tech startups or beginners to learn and build applications. Also, useful for large-scale applications as performance-wise.

[Important] The current version of Nuxt.js is v2.9.2

Reasons why the developers consider Nuxt for any project:

1. Build universal apps without any trouble.


The plus point of the Nuxt.js is that the developers can create universal applications easily in the Vue. Most of the people are not familiar with universal apps basically the beginners.

So, what is a universal app?

It is the app that describes JavaScript code that can execute both on the client and the server-side. There are many modern Javascript frameworks like Vue, that aim to build Single-page Applications (SPA). And a universal app completely based on SPA.

  • Nuxt makes coding more simple:

    It is boring to build long monotonous projects for developers because it needs more time for the configuration on both server-side and client-side. The main aim is to make it simple to share codes between server and client.

    Last but not least, Nuxt gives the developer an asyncData method in the components which use to fetch data and render it on the server-side. This is how Nuxt helps the developers to create universal applications.

2. Provide automatic code-splitting


Nuxt generates a static version of your website with a unique webpack configuration. For every page, it automatically creates the program which builds its own JavaScript file.

Also, it helps to speed up the progressing and keep the size of the JavaScript file small relatively to the application size.

3. Easy to write Single file components


There are many Vue projects using Vue.component, supported by new Vue ({ el: `#container’ }) to target the container element in the body of every page. It is used only to build small projects (single file) where JavaScript is only used to enhance certain views. It has difficulty managing the big file. Use .vue extension with single-file components, to solve your problem.

The installation process of Nuxt.js

  • Syntax to Install Nuxt:
$ npm i nuxt
  • Syntax to create a basic application:
$ npx create-nuxt-app <project-name>

According to the latest update, you can directly start with the CLI create-nuxt-app.

Or start it with a simple template: starter:
The basic Nuxt.js project template express: Nuxt.js + Express koa: Nuxt.js + Koa adonuxt: Nuxt.js + AdonisJS micro: Nuxt.js + Micro nuxtent: Nuxt.js + Nuxtent module for content-heavy sites.

  • Example: Syntax for a basic Hello World app in Nuxt.js
<template>
  <div>
    <h1>Hello world!</h1>
    <NLink to="/about">
      About Page
    </NLink>
  </div>
</template>

Advantages of Nuxt.js

  • The main advantage of Nuxt.js is, its main scope is UI rendering while removing away the client/server distribution.

  • In Nuxt.js you get automatic code-splitting.

  • Statically its render your Vue apps and get all of the benefits of a universal app without a server.

  • You can easily set up transitions between your routes and write single-file components.

  • It provides an auto-updating server for easy development.

  • In Nuxt.js you get ES6/ES7 compilation without any other extra work.

After clear our first concept of Nuxt. Let’s move to the next topic Next.js

next.js


If you compare all three frameworks, the most popular framework you get is Next.js from the other two. Let see what is so interesting in this framework that it is popular and developer’s favorite.

What is Next.js?


Next.js is a Javascript framework that uses React to build server-side rendering and static web applications. According to every developer, it the best tool to build websites because it has great features and advantages, which make it the first option for creating web applications.

So, do you think, why it is the first choice of the developer for building web applications?

The first thing that makes it different from the other two frameworks is it doesn’t need any configuration of webpack. Even it comes with its configuration, with some basic React and Javascript knowledge, build your way to development.

Some of you all know about React, but for beginner, let’s have a quick introduction to React.

What is react?

React is a Javascript library for building user interfaces, it is also known as React.js. It can be used as a base in the development of single-page or mobile applications that make it optimal for fetching rapidly changing. React was created by Facebook.

For using React.js it is important to know about the basic components of React.

Components cab be rendered to a particular element in the DOM by using the React DOM library. There are two primary components in React.

  • Functional components

These are the component which declared with a function that then returns some JSX.

Syntax:

function Greeting(props) {
  return <div>Hello, {props.name}!</div>;
}
  • Class-based components

These are the components declared using ES6 classes and also known as “stateful” components, because their state holds the values throughout the component and can be passed to child components through props.

Syntax:

class ParentComponent extends React.Component {
  state = { color: 'green' };
  render() {
    return (
      <ChildComponent color={this.state.color} />
    );
  }
}

This is all about React let come to our topic Next.js.

Next.js is a framework that is opinionated and provides a structure for the apps. As well as it is an automatic code-splitting.

[Important] The current version of Next.js is Next.js 9

Some reasons to use Next.js to build your project.


Next.js comes with great features that make it useful as well as popular among the developers.

1. Easy to generate website


For beginners or experienced developers, Next.js is the framework easy to use and get started to build a project. It is easy in Next.js to compile and export the application in HTML.

2. Server-side rendering


Next.js performs server-side rendering by default which makes your application optimized for search engines. In this Next.js come with a head component that allows the developers to add or make dynamic Meta-Tags.

By using SSR you get:

  • It provides users an initial render of the applications while loading the code in the background.
  • Easily eliminate the need for the client to download code in HTML format.
  • Also, help to create SEO friendly applications.

3. Routers


When you create any React application by using create-react-app, you usually need to install a react-router and create its custom configuration. But with Next.js it is easier because it comes with its own routers with zero configuration. The main feature is that Next.js take care of all its routers you just sit and create your page inside the pages folder.

The Installation Process of Next.js

  • Syntax to install Next.js:
npm install --save next react react-dom
  • Syntax to add a script to your package.json:
{
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }
}

After that, the file-system is the main API. Every.js file program that gets automatically processed and rendered.

  • Example: Syntax for a basic Hello World app in Next.js

Use ./pages/index.js inside your project

function Home() {
  return <div>Hello world!</div>;
}

export default Home;

Then run npm run dev.

Advantages of using Next.js

  • Next.js is easy to deploy anywhere with Node.js support.

  • It can be executed with Express or any other Node.js HTTP server.

  • Any unnecessary code is not loaded in Next.js.

  • Webpack-based dev environment which supports Hot Module Replacement (HMR).

  • Fetch data easily.

  • Next.js is simple client-side routing (page=based).

  • Every component is server-rendered by default in Next.js.

  • As well as, automatic code-splitting which use for faster page loads.

Here we complete our two concepts Nust.js and Next.js, let’s move to the last topic Nest.js

nest.js


The main thing that makes Nest.js differ from both the frameworks is that it is heavily inspired by Angular.

What is Nest.js?


Nest.js is a framework for building efficient, scalable Node.js server-side applications. It is the modern JavaScript, which is built with TypeScript and uses Express.js. The important thing that Nest.js provides that it preserves compatibility with pure JavaScript and the combine elements of OOP (Object-Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

As similar to TypeScript and a reasonable knowledge of JavaScript help the developer to create the best application in Nest.js. The main aim of Nest.js was to solve the architectural problems of Node.js by providing back-end applications a modular structure for organizing code into separate modules. The plus point to work in Nest.js that it is fully built with TypeScript which is really beneficial for code type checking by which it helps to facilitate the process of development of the application.

[Imprtant] The current version of Nest.js is version5

Recently, the Nest.js framework is increasing popularity due to its incredible features:

Some features of Nest.js

  • Nest.js is open-source (MIT license).

  • It is easy to use, learn and develop applications.

  • It is a powerful command-line interface (CLI) tool that boosts your productivity.

  • It has detailed and well-maintained documentation.

  • Also, supports specific modules that help you easily integrate with common technologies and concepts such as TypeORM, Mongoose, GraphQL, Logging, Validation, Caching, and Websockets.

  • Also, provide active codebase development and maintenance.

  • Leverages typescript which means it is a strongly typed language that super-set of JavaScript.

  • Easy to unit testing applications.

  • The Nest.js is made for Monoliths and Micro-services (entire section in the documentation regarding the Microservice type of a NestJS application, as well as techniques and recipes).

Nest.js provide the developers with an out-of-the-box application structure that allows them to create highly testable, scalable and easily maintainable applications. As well as it makes use of Express which provides compatibility with a wide range of other libraries that the developer easily uses the myriad third-party plugins which are available.

The Installation of Nest.js

  • Syntax to install Nest.js
$ npm i @nestjs/cli
$ nest new project-name
  • Example: Syntax for basic Hello World app in Nest.js

    Remember, after installing Nest.js with the npm cli command, and to create a new project with nest new project-name.
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  await app.listen(2000);
}
bootstrap();

And then to run the app listen on port 2000, you execute the syntax:

$ npm run start

Advantages of using Nest.js

  • The main advantage of the Nest.js is that it has a TypeScript-based web framework, that possible to build any strict type application.

  • The framework of Nest.js is very annotation-driven which generates everything to make you easy.

  • The project that builds in Nest.js is heavily based on Angular.

  • As you know Nest.js is a module-based framework, by which it is easy to externalize general-purpose modules and reuse code in multiple projects.

  • The important advantage of the Nest.js is that it uses the latest version of TypeScript that helps the developers to code less and gets productive work. And this is the same with Angular.

Just Remember

Nust– This is the framework to create a Vue application that supports universal rendering.

AND

Next- This is to create a React application that also supports universal rendering.

AND

Nest– This for node applications with additional structure and support.