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 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
React Developers React Native Developers React Native Web

How to do navigation in React native web in 2020

“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, or if you are planning to build a website along with an app, you should definitely learn React native web.

Setting up navigation in reactnativeweb is challenging as the navigation system works quite differently in apps vs browser.

In this article, we’ll set up the most popular react-navigation on to react-native-web.

Using React navigation in react native web

React navigation is the most famous library for navigation in reactnative. In this section, we’ll try to integrate react-navigation in reactnativeweb.

Prerequisite

For this setup, we’ll be using expo as the platform on which we’ll be building our reactnative app, which will run on android, ios, and the web.
Make sure you have expo-cli installed already.

To set up your codebase using expo, check this GitHub link [master branch]. Simply clone the branch and do run expo start

If you are looking for a quick code, then you can check this GitHub link [NOTE: the branch is reactnavigationsetup and not master.]

Installation

Run the following command to install reactnavigation along with other needed packages including reactnavigationstack.


expo install react-navigation react-native-gesture-handler react-native-reanimated react-native-screens


npm i react-navigation-stack
npm i @react-navigation/web

Check your package.json files to ensure all of the above packages are installed, make sure reactnavigation is version 4+. If you are wondering, why did we use expo instead of NPM/yarn while installing reactnavigation, then the reason is that expo would look for the correct version of the reactnavigation libraries that’d work with the expo version that’s installed in your project.

If you look into the printed console it uses NPM underneath.

Create a few screens

Now, let’s set up a few screens to test our navigation flow:

  • Profile screen
  • Post screen

// feed screen

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

export default class Feed extends React.Component {

    render() {
        return <View style={styles.container}>
            <Text>This is the feed screen</Text>
           <Button
                    title="Go to Profile"
                    onPress={() => this.props.navigation.navigate('Profile')}
            />


        </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
})

The above is the code for FeedScreen, which is a simple text, and a button. The button when clicked should go directly to the profile screen.


// Profile screen

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

export default class Profile extends React.Component {

    render() {
        return <View style={styles.container}>
            <Text>This is the profile screen</Text>
            <Button
                title="Go to Feed"
                onPress={() => this.props.navigation.navigate('Feed')}
            />

        </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
})

The Profile screen is the same as the Feed screen. Both the screens have a button which takes to the other screen.


Let’s also create stack navigation to connect these two screens together:

// Home.js, just a name of the stack navigation

import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';

import Feed from "../screens/Feed";
import Profile from "../screens/Profile";


const Home = createStackNavigator(
    {
        Profile: Profile,
        Feed: Feed,
    },
    {
        navigationOptions: {
            headerTintColor: '#fff',
            headerStyle: {
                backgroundColor: '#000',
            },
        },
    }
);

const container = createAppContainer(Home);

export default container;

Since the object that’s passed to CreateStackNavigator Profile comes first, the Profile screen is the default screen of this stack navigator.

Now, in the App.js file, simply render the Home Navigation.


// App.js

export default function App() {
  return (
    <View style={styles.outer}>
      <Home/>
    </View>
  );
}

Just run the app using command expo start , and it should launch the expo bundler for you.

If you press i to launch the Expo app in the IOS simulator in the terminal, the following screen comes up on display, if everything goes well.

When you click on the Go to Feed button, it should take you to the feed screen.

To run the same setup on to the web, simply press w in your terminal, it will launch the web app in your default browser.

The click functionality also works on the web as well. The top border is for the screen title, you can add it by adding navigationOptions to the feed and profile screen like this.


export default class Feed extends React.Component {
    static navigationOptions = {
        title: "Feed"
    }
...

But there is one problem with the web navigation, the URL doesn’t change when you go from the profile to the feed screen.
In the web navigation, it is extremely important to have the change in page reflecting in the URL as well.

In the app, there is no way a user can directly jump to a screen other than the default screen, but in the browser it is possible, a user can enter a URL.

The good part of reactnavigation is that it supports URL updates when the screen changes. The way navigationOptions is added inside the screen class similarly you can also add title.


export default class Feed extends React.Component {
    static navigationOptions = {
        title: "Feed"
    }

    static path = "feed";

    render() {
...

For the profile screen, you can keep the path as empty static path = "".


When you go to http://localhost:19006/feed, the web app would understand that you want to go to the feed screen and will render that for you. Try going to http://localhost:19006/feed directly, and it should render the feed page for you.

But when you click on the Go to Feed button, the URL won’t change.

There are a few other things that we need to do to make this work:
@react-navigation/web also provide Link module which gets converted into a tag on to the web.

And, this module doesn’t work when you try to run the app. So, we use Platform module provided by reactnative to differentiate between web and app.


// feed screen

import React from 'react';
import {View, Text, StyleSheet, Button, Platform} from 'react-native';
import {Link} from "@react-navigation/web";

const isWeb = Platform.OS === 'web';


export default class Feed extends React.Component {
    static navigationOptions = {
        title: "Feed"
    }

    static path = "feed";

    render() {
        return <View style={styles.container}>
            <Text>This is the feed screen</Text>
            {
                !isWeb ? <Button
                    title="Go to Profile"
                    onPress={() => this.props.navigation.navigate('Profile')}
            />:  <Link routeName="Profile">Go Profile</Link>

            }


        </View>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
})

Here, we are conditionally rendering the Link and the Button.

You need to do similar changes for the Profile screen as well. Also, in the navigation container, instead of createAppContainer you need to use createBrowserApp for the web.

Here is the code for the navigation:


// Home.js, just a name of the stack navigation

import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import {createBrowserApp} from '@react-navigation/web';

import Feed from "../screens/Feed";
import Profile from "../screens/Profile";
import {Platform} from "react-native";

const isWeb = Platform.OS === 'web';


const Home = createStackNavigator(
    {
        Profile: Profile,
        Feed: Feed,
    },
    {
        navigationOptions: {
            headerTintColor: '#fff',
            headerStyle: {
                backgroundColor: '#000',
            },
        },
    }
);

const container = isWeb ? createBrowserApp(Home): createAppContainer(Home);

export default container;

Try running the app in the browser, Go to feed button click should change the URL to http://localhost:19006/feed.

Also, the app should be running fine on the simulators as well.

In the following videos, I have done the walkthrough of the reactnavigation setup on react native web.

Categories
React Developers React Native Developers

12 Places To Hire Top React Developers In 2020

When building/ growing a new company or managing an established business, one aspect that affects the overall success of an organization is to learn to hire an efficient workforce that fits the bill perfectly for the company’s growth.

It becomes even more crucial to select great people when you are hiring for a new business. Hiring top react developers has become even more difficult in the last few years because of its growing popularity and usability amongst companies of all sizes.

Hire top react developers

React developer’s salary trends are also showing a stable rise and currently, an average React.Js Developer salary in the USA is $125,000 per year or $64.10 per hour. Entry-level positions start at $68,250 per year while most experienced workers make up to $183,500 per year.

This new Javascript development framework eases the data management and content maintenance of the websites. As new reports suggest ‘React.js‘ is powering more than 45% of internet websites which is a fairly bigger market proportion to capture, considering it is a fairly new technology.

Since every new business-like ‘Paypal‘ or stalwarts like ‘BBC‘ or ‘Newyork Times‘ and many others are using React.js to build their mobile applications etc., the demand to hire top react developers is on an all-time high. Also, it makes sense to work on React technology because of the super successful advantages it lends to the react developers.

React technology
Hiring top react developers with great skills is getting difficult day by day

An additional advantage of working with talented best developers is that a lot of your stress and hassles are efficiently taken care of by hard-working team members, who take the ownership to deliver the end product and deliver it at the right time. This creates a pleasurable, smooth working experience for both the employee and the employers.

Let’s see some of the best places to hire top react developers for your next project, which will help you build a top-notch, great performing team and business and simplify your search for talented react developers. The list is prepared on many crucial factors like customer satisfaction, employer satisfaction, third-party websites, company portfolio, keyword analysis tool, and much more useful considerations.

LinkedIn

This American business and employment-oriented service is the wholly-owned subsidiary of Microsoft and has 630 million registered members in 200 countries. It is mainly used for professional networking, where employers post jobs and job seekers post their CVs.

LinkedInfor react developer
LinkedIn offers many opportunities to hire top react developers

Angelist

This platform is on a mission to democratize the investment process and to help startups with their challenges in fundraising and talent.  It is primarily a US based site for job-seekers, startups, and angel investors. Angelist is providing 2 million plus tech and start-up job opportunities and making high-quality candidates accessible to employers. They have 2,300,000+ candidates including 750,000+ developers, 170,000+ designers, and thousands more every day.

Angelist to hire react developer
Top global website for job-seekers, start-ups and angel investors

Codersera

If you are looking for the best React experts for your projects then go Codersera, it is a wonderful platform to hire top react developers. Codersera is a fresh start-up and has earned a quick reputation for its stringent work ethics with structured and matured work policies.

Hire top react developer
A wonderful platform to hire superior quality React developers for projects of any size

Overall it is a great platform, quite superior from other such platforms in terms of professionalism, technical knowledge, work ethics, passion and dedication for their taken projects. Codersera is suitable for projects of any size as they have developers of many skill levels. Their 24/7 dedicated team of highly skilled technocrats, hired through a 5-tier rigorous screening procedure assures a quality product delivery.

Arc.dev

Previously known as CodementorX, arc.dev is a community of over 2k expert React freelancers across the globe. It is a sisterly branch of learning platform Codementor.

They allot one project manager specifically for your project and a shortlist of candidates, which one is free to interview for trial runs. After that you get to directly work with the chosen developer and be asured to get a quality product delivered absolutely on time.

When you have an urgent requirement for a developer, it definitely is the best place to visit. And there are no extra fees except for the payment you make for the hiring of your project.

React developer
Great platform to hire top react freelancers

Toptal

Toptal helps you in finding a perfect freelancer for your project and that too at an economical price and they guarantee a highquality product delivered by refined expertise.

Toptal also has a rigorous screening process to hire their developers which only 3% of applicants clear through which means that a great quality work will be done. It simplifies many things, making it easier to hire top react developers and get started.

Hire react developer
Toptal is renowned for providing high-end quality product delivered at economical prices

X-Team

X-Team provides high-performing, great team of React developers and is catering to many successful projects through their great teamwork and passion for development.

Hire react developer
X-Team specialises in React.js development

The XTeam gives out an open call to freelancers, inviting the talented and brightest minds to be a part of X-Team. One of their main specialties is React.js and many of their React experts have worked with Twitter, Fox, and riot games.

Workopolis

Workopolis is a leading Canadian career website providing job services to millions for over 15 years now. Workopolis is committed to making best talent pool reach their target employers without any hassles.

Hire react native developer
Workopolis is committed to providing best talent pool

Dice

Dice connects people to companies. Dice is a high-end recruiting platform that’s perfect for large projects requiring only the best. Hiring from Dice is slightly expensive, but its all worth for the extra features one gets to enjoy. Social recruiting, email advertising, access to resumes, includes applicant screening, so one doesn’t has to bother about all these.

React developers salary
Dice connects workforce to companies

Monster

Monster.com is a global gigantic employment website providing jobs to millions every day and if someone looking to hire react developers for their projects, this job search engine is a must visit.

Hire top react developer

Monster.com is a must visit search engine to hire top react developers

StackOverflow

Stack Overflow is a great place to find talented React developers of all skill levels. Stack Overflow is one of the most reliable job boards on the net, where employers can hire locally or remotely.

Hire react developer
Stackoverflow is considered a great place to hire top react developers of all skill levels

Valuecoder

Valuecoders are renowned for providing high-end quality software development services to build web and mobile applications. They outsource dedicated software development teams for various project needs of your businesses.

Hire top react developer
Valuecoders outsource dedicated software development teams for various projects


With over 4k projects under their belt, they have extensive experience of delivering successful projects.

Glassdoor

Glassdoor is a website where current and former employees anonymously review companies. Glassdoor allows users to search and apply for jobs as well as anonymously submit and view salaries on its platform. The company was acquired by the Japanese firm, Recruit Holdings in 2018 and is headquartered in California, with additional offices in cities around the world.

Glassdoor is used to apply for jobs as well as review companies


SUMMARY

React is a relatively new javascript library, used for building beautiful user interfaces and is designed for front-end development of single page and mobile applications. React is rapidly overtaking other front-end development frameworks like Angular etc. and it is getting very difficult to find talented people who know the technology very well. Hopefully, you find this list a great relief in simplifying your search to get connected to the best React developers for your business needs. The list has emphasized on providing a detailed data about hiring top React freelance developers as well as full-time employees for your React technology projects.

Categories
React Developers React Native Developers

Is Expo Eject a Good Idea?

What is Expo?

Expo is a framework/ platform for React applications providing a set of tools built around React Native and native platforms. It helps developers build, deploy, develop and quickly iterate on iOS, Android, and web apps from the same JavaScript/TypeScript codebase.

React native with expo

Use case of expo eject

Are you planning to eject expo from your react-native app? If yes, I hope the following are the use cases that you’d have.

    1- You want to add an “NPM” package to your project which requires a reactnative link. And as a rule of thumb, if the documentation for a third-party package states that you need to run the command react-native link as part of the setup process, then this package can’t be used with expo.


    2- You are more of a native (Java/Kotlin/Swift/Objective C) person, and want to integrate native module into your Reactnative app but couldn’t find a way to do it in the expo, so want to get rid of it?


    3- You want to add an awesome push notification library like OneSignal in your app which expo doesn’t support.

Are there some other reasons? If yes, write in the comment box below, and I’ll personally look and reply.


Before ejecting Expo, let’s have a look at the drawbacks that you’d face:


Once you eject expo, you can’t inject it back. So, all the great development experience that you had with expo is gone now. Typically to develop a feature in non-expo takes almost 3x the time as compared to expo.

If the developer chooses to eject from Expo, these great development features of the Expo are lost and it takes almost 3x the time as compared to the expo to develop those features in the non-expo state.

Some Advantages Of Using Expo


Expo is kind of an extension to ReactNative that offers a bunch of components and libraries already included to facilitate the development of mobile apps with React Native. Let’s see a few of them:

  • Fast and simple project installation.
  • Opens a convenient utility Expo CLI in a browser and facilitates ‘app status’ checking on the device it runs on, scan QR code, send the link via email to open the app in Expo Client, or switch the production/ development mode and publish your app on expo server.
  • Develop from Windows/macOS or whatever you just only need Nodejs and an internet connection.
  • Library linking with reactnative links not necessary as everything is covered by the expo.
  • Expo client is an app that is easily installed from the Google Play Store or Apple Store on your phone. It allows the opening of projects without build via XCode or Android Studio during the development process. With Expo Client, the apps can be sent to others for review which is greatly required when testing without any need of creating APK or IPA files.
  • The app can be updated over the air without repeated deployment on Google Play Store or Apple Store. When users open the app, it will automatically update the app by pulling the recent js bundle published on the expo server.
  • Automatic management of certificates and app signatures.
  •  Easy to use and gives the intermediate results fast.
  •  Test directly on the device for both iOS and Android.
  •  One can develop apps for ios without macOS with ios device and test them with Expo client
  • Expo SDK offers the collection of ready solutions, such as working with the device accelerometer, camera, notifications, geolocation, etc.

The expo team regularly updates the SDK with new solutions which is very useful for the user.


Let’s look into each use case of “expo eject” one by one:

1. Want to add an “NPM” package that requires linking: The thing that you should ask yourselves is, are there some other packages which don’t require linking and still solves the purpose? Most of the time, you’d find that such a solution already exists. The Expo community has already included many useful packages in the build and the users are just not aware of it. Be it SVGs, animation, or video, most of the packages are already in the expo. If you couldn’t find the replacement package in expo, then there is no way apart from expo eject.

2. You want to add your written custom native module: When writing your reactnative bridge and of which the ‘NPM’ package doesn’t exist yet, for such a scenario the Expo eject is the only way and it has to be done.

3. Third-party notification library like OneSignal: Before integrating any awesome push notification service, you’d first explore the push notification service of expo. Although, Expo’s push notification service isn’t great but it solves the purpose in most of the cases. If you don’t like it, and still want to integrate OneSignal or other notification services, then expo eject is the way out.

So far we have seen that in some of the cases, expo eject has to be done. And expo itself says that here

But wait, what if I tell you that there is a way in which you can add custom native modules in expo without ejecting it.
Well, my above statement is not totally true. You have to eject it, but you won’t lose any of the benefits that you were getting with expo. You can still use the modules provided by expo, you can still have the same development flow, you don’t need to re-build native modules over and over again, you don’t need to worry about pod files, swift, kotlin etc.

Won’t that be great? In the following blog, I have described in detail how you can run expo along with custom native modules, or simply do react-native link with expo


Categories
Backend Developer Database Programming React Developers

Hooks, Getting in a New Relationship

Introducing React Hooks


In 2018, at the React Conference “Hooks” was officially Introduced to React.

Hooks arrived as a savior for developers who were struggling in maintaining hundreds of states for hundreds of components.

They let you use state and other React features without writing a class. Now, you can kick out classes from your components.

No need to worry, There are no plans to remove classes from React permanently, yet

You can adopt Hooks gradually,
Hooks work side-by-side with existing code so there is no rush to migrate to Hooks.

You don’t have to learn or use Hooks right now if you don’t want to.

WHY GO FOR HOOKS?

You might be thinking why you need to learn one more feature? The answer is here:

  • It helps when you need to maintain too many components and states.
  • Completely opt-in.
    You can try Hooks in a few components without rewriting any existing code.
  • A “wrapper hell” of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could filter them out in DevTools, this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic, here Hooks made an appearance.
  • With Hooks code Reusability is improved, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.
  • render props and higher-order components try to solve some problems but make code harder to follow, because it requires to restructure your components.
  • components might perform some data fetching in componentDidMount and componentDidUpdate. However, the same componentDidMount method might also contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
  • It’s not always possible to break these components into smaller ones because the stateful logic is all over the place. It’s also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library.
  • class components can encourage unintentional patterns that make these optimizations fall back to a slower path

How Hooks Affect the Coding Style

  • Say bye! to class
Without Hooks:

Class Components

class Clock extends React.Component {
    ...
    ...
    render() {
        return (
            <div>
                <h1>...something...</h1>
            </div>
        );
    }
}
With Hooks:

Function Components

function Example() {
    ... // Hooks can be used here
    ...
    render() {
        return (
            <div>
                <h1>...something...</h1>
            </div>
        );
    }
}
OR like this:
function Example = () => {
    ... // Hooks can be used here
    ...
    render() {
        return (
            <div>
                <h1>...something...</h1>
            </div>
        );
    }
}

> you can also pass props to the function:

function Example(props) {
    ... // Hooks can be used here
    ...
}
OR like this:
function Example = (props) => {
    ... // Hooks can be used here
    ...
}

props can be accessed like this -> const v = props.value

  • Creating a local state
Without Hooks:
const state = {
    x: 10,
    y: 'hello',
    z: {
        word: "world!"
    }
}
With Hooks:

useState is used to set the initial value for a local state.

// this is How we declare a new state variable
const [color, setColor] = useState('Yellow');

// declaring multiple state variables
const [x, setX] = useState(10);
const [y, setY] = useState('hello');
const [z, setZ] = useState([{
    word: "world!",     
}]);
  • Accessing state: a Breakup With this
Without Hooks:
constructor(props) {
    this.state = { text: 'demo' };
}

render() {
    return (
        <div>
            <h1>This is { this.state.text }</h1>
        </div>
    );
}
With Hooks:

While using hooks, state variables can be accessed directly

const [text, setText] = useState('demo');

render() {
    return (
        <div>
            <h1>This is { text }</h1>
        </div>
    );
}
  • Changing the State
Without Hooks:
...
this.state = {
    a: 1,
    b: 2,
    fruit: 'apple'
}

...
{
    this.setState({
        ...state,
        fruit: 'orange'
    });
}
With Hooks:
const [fruit, setFruit] = useState('apple');

...
{
    setFruit('orange')
}
  • Effect of the Effect Hook
  • React runs the effects after every render, including the first render.
  • With useEffect() we can run a script after each update or after a particular change.
  • Lifecycle methods componentDidMount, componentDidUpdate or componentWillUnmount can be replaced with useEffect()
// To run with each Update
useEffect(() => {
    // Do something
});


// run only when value of "color" is changed
useEffect(() => {
    // Do something
}, [color]);


// run only on first render
useEffect(() => {
    // Do something
}, []);

Let’s see some usages, in lifecycle methods
— ComponentDidMount

Without Hooks:
componentDidMount() {
    // do something
    const cat = "tom";
    this.setState({
        ...state,
        animal: cat
    });
}
With Hooks:
useEffect(() => {
    // Do Something
    const cat = "tom";
    setAnimal(cat);
}, []);

— ComponentDidUpdate

Without Hooks:
componentDidUpdate() {
    // do something
    const cat = "tom";
    this.setState({
        ...state,
        animal: cat
    });
}
With Hooks:
useEffect(() => {
    // Do Something
    const cat = "tom";
    setAnimal(cat);
})

above snippet will run the code at every update including the first render acting as a combination of componentDidMount and componentDidUpdate, if you want to prevent it from running on first render, then it can be done by keeping a check of first render, like this:

const [isFirstRender, setIsFirstRender] = useState(true);

useEffect(() => {
    if (isFirstRender) {
        setIsFirstRender(false);
    } else {
        // do Something
        const cat = "tom";
        setAnimal(cat);
    }
}

— ComponentWillUnmount

Without Hooks:

componentWillUnmount() {
    // Do Something
}
With Hooks:

Just return a function ( named or anonymous ) for cleanup, that we do in ComponentWillUnmount

useEffect(() => { 
    return () => {
        // Do something
    }
});
  • Getting the context with the Context Hook

useContext() takes a context object as the parameter and returns the corresponding context values at that time. Refer to the example below for a better understanding.

// for example, We have
const flowers = {
    sunflower: {
        petals: 25,
        color: "yellow"
    },
    daisy: {
        petals: 5,
        color: "white"
    },
    rose: {
        petals: 30,
        color: red
    }
};


// Creating our context
const MyContext = React.createContext( flowers.rose );


// Wrappin the component with <MyContext.Provider>
function App() {
    return (
        <MyContext.Provider value={ flowers.sunflower }>
            <MyComponent />
        </MyContext.Provider>
    )
}

The current context value is determined by the value of the value prop passed in the nearest <MyContext.Provider> in which the component is wrapped.

// ... somewhere in our function component ...
const flower = useContext(MyContext);

Now the flower will have the value of rose:
{ petals: 30, color: "red" }
and can be used as
<p>Colour of rose is { flower.color }.</p>
It will run each time when the context is updated

You must have got the ‘context‘ of this blog if you are still here, kindly have a look at “Some rules to remember” below:

Some rules to remember

  • never be conditional with Hooks:
    don’t call hooks inside loops or conditions, call Hooks at the Top level
  • don’t call hooks from nested functions:
    call only from React Function components or custom hooks
    More details can be found in official React docs, available here

More about Hooks

More Hooks

Some other commonly used Hooks are:

Custom Hooks

A custom Hook is a function whose name starts with ”use” and that may call other Hooks and, lets you extract component logic into reusable functions.

Let’s create a custom Hook useColor that returns the color of the flower whose ID is passed as argument:

function useColor(flowerID) {
    const [color, setColor] = useColor(null);

    useEffect(() => {
        /*    Extract the value of colour of the flower from the database and set the value of color using setColor()    */
    });

    return color;
}

Now, we can use our custom hook,

{
    // To get the colour of the flower with ID = 10
    const color = useColor(10);
}

Learn more about how to create the custom hooks in detail.

See official docs for React Hooks.

Categories
React Developers

Hire React Developers

In a shorter span of time ReactJS has gained spotlight amongst developers and is emerging as the top choice for businesses and brands because of the innumerable benefits it offers. Apparently, ReactJS is strongly associated with successful brands like BBC, Instagram, Netflix, PayPal, and many such popular brands.

According to Similar tech reports, the United States of America is the leading country globally HIRING react developers as compared to other nations like Japan, China, Russia, UK, etc.

React is a component-based library, used to develop interactive User Interface. Presently, it boasts of a strong foundation and community support and is the undisputed king as one of the most popular JavaScript front-end libraries. React is a component-based library which is used to develop interactive UI’s.

React came, saw and conquered because of being a dynamic, adaptable and Robust programming library!!

React was developed by ‘Jordon Walke’ of Facebook in 2011 and released in 2013. Since then, it’s no looking back for React and its enamoring the developers and users with its dynamic User Interface(UI). The winning point of React JS is its simplicity that makes use of single components where the developer can segregate the difficult UI components into individual ones.

React’s Github repository has collected more than 96,000 stars from users and has garnered a strength of approximately 1200 active contributors, regularly pushing the updates to enrich its library. With over 7 million downloads, the library has proven its mettle with technology companies

In this article, we’ll see advantages to hire react developers for better productivity and the best place to hire talented react developer:

Hire react developers
REACT GROWING ITS BASE AND GIVING UNLIMITED REASONS TO DEVELOPERS TO CHOOSE IT OVER OTHER FRAMEWORKS

Hire React Developers For Your Business Projects For Following Benefits:

Hire reaact developers
Hire Developers
  • Amazing front-end Development Experience:
  • Seo Friendly Environment
  • Improved Productivity
  • Better Code Stability
  • Easy To Learn And Adapt
  • Conducive For Start-Ups As Well Established Businesses

Where can you Find Talented React Developers?

If you are looking for the best React developers for your projects then Codersera is the answer to all your unresolved queries. Hiring top react developers has become even more difficult these days, because of its growing popularity and usability amongst companies of all sizes.

It is a wonderful platform to hire top react developers who are renowned for providing high-end quality software development services to build web and mobile applications.


Go Codersera

Codersera is a global community of the best talent pool of software industry taking great pride in the skills and expertise of their coders, designers, CTOs, PMs and QAs. They envision a future of constant innovations, driven by continuous learning agenda catering to the present market conditions. Today, they are a strong base of 500+ happy clients and 5000+ remote talent.

  • Codersera has been pushing the limits of delivering complex business challenges by providing innovative technical expert solutions and redefining the operational standards.
  • Codersera specializes in outsourcing dedicated software development teams for various project needs of any sizes as they have developers of many skill levels, who can deliver difficult react projects in time.
  • Also, their 1-week risk-free policy is another feather in the cap, where they provide a 1-week risk-free trial absolutely free of cost. The trial phase is for thoroughly testing the given features so that the clients get to make an informed, educated decision.

Additionally, their 24/7 dedicated team of highly skilled technocrats, hired through a 5-tier rigorous screening procedure assures a quality product delivery.

Overall it is a great platform, quite superior in terms of professionalism, technical knowledge, work ethics, passion and dedication for their taken projects.

Why Codersera

1. 5-Tier Screening Process

Codersera deploys the best talent in technology through a rigorous 5-tier screening that assures quality products delivered absolutely hassle-free and only 1% of candidates are able to clear this.

1.1. Resume filtering 
2.2. Video Interview 
3.3. Coding Test 
4.4. Live screening
5.4. Test Project

Resume Filtering

The resume goes through the filtering process on various parameters which only 25% get through. And the candidates are tested for:
– Enough experience for the position
– Passion for technology

Video Interview

The candidate goes through a personality review round on the video interview platforms and is evaluated on their communication skills and knowledge about the domain subject. Only 10% of candidates are able to clear this round ensuring top quality suitable candidates selected for your projects.

Coding test

After clarifying the personality round, the candidate is sent the online coding questionnaire, which they are supposed to solve within a fix time slot of 90 minutes. This filters them on problem-solving abilities and analytic skills and only 4% of candidates are able to get past this round of exhaustive technical scrutiny.

Live Screening
This round is quite similar to the previous round, except the only difference is that a live Codersera expert is there to judge and assist you while you are solving the problem, and only 2% of candidates get past this round successfully.

During this stage the candidates are again tested on:
– Technical Skills
– Soft skills (Communication, English level, Teamwork)
Test Project

During this final and the most crucial round, the chosen candidates are sent a project that is quite similar to the real-life projects which they are supposed to finish in 1-2 weeks of given time.

Generally, this requires to build a full-stack application similar to real-time client requirements and only 1% of candidates are able to come out a winner in this.

2. 1-Week Risk-Free Trial Policy

Also, they provide a zero-risk platform with a one-week free trial period that ensures top quality end product delivered through transparent evaluation procedure, specially curated to meet client’s requirements and suitability. Working with their creatively advanced design thinking provides innovative technical assistance to solve all types of complex business challenges.

3. Fast-end Delivery

Codersera is committed to fast end delivery to match their expertise and do justice to industry standards through passion, education, skills and ethical values for work.

How a Company Hire ReactJS Developers from Codersera:


Codersera has a simple and easy procedure for its esteemed clients that comes with an added advantage of 1-week risk-free policy too:

  • First of all, the client/ company share their project requirement on Codersera’s website.
  • Codersera project evaluation department analyzes the project requirements and completion dates thoroughly in detail and if found feasible, allots a developer matching that domain.
  • Before the beginning of the risk-free trial period of 1-week, the client is made to sign an NDA (Non-disclosure agreement) and you are all set to a hassle-free smooth experience of your project development.
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);