Saturday, February 27, 2021

React Hooks

Earlier on in React, components were either class components or functional components. Functional components were Javascript functions that accepted props (data) to display and returned JSX.

Class components typically required more code but could store state variables and could use lifecycle methods. This made class components the go-to option for making API calls, processing user input, etc. Functional components became useful helpers for class components.

With the release of React 16.8 in 2019, React Hooks have finally become available to use in our production applications. This allows React developers to make functional components stateful. Instead of using a class component to hold stateful logic, we can use functional components.

React Hooks are not available in class-based components — but instead they allow you to use React without JavaScript classes. If you prefer to use functions instead of classes (which is recommended in JavaScript) you can simply start using Hooks without worrying about migrating your whole apps to classes.

Hooks enable you to use “class-features” In React by providing a set of built-in functions such as:

  • The useState() hook for using states from function components,
  • The useEffect() hook for performing side effects from function components (It's equivalent to life-cycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in React classes). 

Hook State

let’s set up a component with state, the hooks way.


import React from "react";
const HookDemo = () => {
  return (
    <div>
      <h2>React Hooks</h2>
    </div>
  );
};
export default App;

 

And now, let’s use a React hook. We’ll add in some state to the component . To do so, we’ll import the useState hook from React at the top of the App.js file:


import React, { useState } from 'react';

Then we’ll apply the useState hook at the top of the App component function, to set up state functionality for the stuRoll:


const HookDemo = () => {
const [stuRollsetStuRoll] = useState();
 

There are three aspects to the useState hook:

1.   The argument to useState is its initial value. Therefore, with useState(), we are setting the initial value of stuRoll to a blank value.

2.   The useState method destructures your state object into an array of two values. The first one is the current value of the variable that is being tracked in the component state. Therefore, in const [stuRollsetStuRoll] = useState()stuRoll represents that current value. It becomes a constant that can be used in the component code.

3.   The second value returned from the useState function is a function itself. This function updates the paired state variable. So setStuRoll updates the stuRoll value.

Within the App component, let’s create a helper method, called updateDataWith this method, the input element will set the stuRoll in the hook state. How?

This helper will call the new setStuRoll function and update the student Rollno.

const ReactDemo = () => {

const [stuRollsetStuRoll] = useState(0);

  const updateData = () => {

    setStuRoll(10);

    console.log("Updated RollNo"stuRoll);
  };

  return (
    <div>
 <h2>Hooks | Function Component Based</h2>
      <h3>RollNo: {stuRoll}</h3>
      <button onClick={updateData}>Update</button>
    </div>
  );
};

export default ReactDemo;


Comparison to traditional class Component state

Let’s compare the App component function above with the more traditional class component state approach:

import React, { Component } from "react";

class StateDemo extends React.Component {
  constructor() {
    super();
    this.state = {
      stuRoll: 0,
    };
  }
  updateData = () => {
    this.setState({ stuRoll: 10 });
  };
  render() {
    return (
      <div>
        <h2>State | Class Component Based </h2>
        <h3>RollNo: {this.state.stuRoll}</h3>
        <button onClick={this.updateData}>Update</button>
      </div>
    );
  }
}
export default StateDemo;




Take note of the differences between this function version and the class version. It’s already much more compact and easier to understand than the class version, yet they both do exactly the same thing. Let’s go over the differences:

  • The entire class constructor has been replaced by the useState Hook, which only consists of a single line.
  • Because the useState Hook outputs local variables, you no longer need to use the this keyword to reference your function or state variables. Honestly, this is a major pain for most JavaScript developers, as it’s not always clear when you should use this.
  • The JSX code is now cleaner as you can reference local state values without using this.state.

Hook with Multiple states

import React, { useStateuseEffect } from "react";

const ReactDemo = () => {
  const [stuRollsetStuRoll] = useState(0);
  const [stuNamesetStuName] = useState("---");

  // Update the data of the component
  const updateData = () => {
    setStuRoll(10);
    setStuName("Pankaj");
  };

  return (
    <div>
      <h2>Hooks with Multiple States</h2>
      <h3>RollNo: {stuRoll}</h3>
      <h3>Name: {stuName}</h3>
      <button onClick={updateData}>Update</button>
    </div>
  );
};

export default ReactDemo;




The Rules of Hooks

  1. Hooks can only be called at the Top Level, it can't be called inside the loops or condition or nested functions.
  2. Hooks can only be called in the React Function or Custom Hooks, never use hooks in the regular javascript function.

Hooks Effect 

The Hooks Effect enables us to conduct collateral effects within the components function. The Hooks Effect will not use the lifecycle methods of the components, and these methods exist in the class components. Hooks Effect is similar to componentDidUpdate(), componentDidMount() lifecycle methods.


import React, { useStateuseEffect from "react";

const ReactDemo = () => {
  const [stuRollsetStuRoll] = useState(0);
  const [stuNamesetStuName] = useState("---");

  // Similar to componentDidMount() and componentDidUpdate

  useEffect(() => {
    console.log("Hooks Effects called ");
  });

  // Update the data of the component
  const updateData = () => {
    setStuRoll(10);
    setStuName("Pankaj");
  };

  return (
    <div>
      <h2>Hooks with UseEffect</h2>
      <h3>RollNo: {stuRoll}</h3>
      <h3>Name: {stuName}</h3>
      <button onClick={updateData}>Update</button>
    </div>
  );
};
export default ReactDemo;



In the above code, we invoke “useEffect” to inform the React to execute the “effect” method after reddening the modifications in the DOM. As we declare the effects in a component, the effects can use the state and props. React implements the effects after each render. Effects may also define how to do “clean up”.

Side effects contain usual properties that every web application have to conduct, like:

·       DOM Updation

·       Consuming and Retrieving data from an API Server.

·       Establishing Subscription 


Side Effects

we categorize side effects into two types:

  • Effects with Cleanup: After updating the DOM, we have to clean up some effects. For example, when we need to establish a subscription for any explicit data source, it is essential to clean up the memory to ensure that there is no memory leak.
  • Effects without Cleanup: We use Effects without Cleanup in effect that does not obstruct the browser in screen updation. Examples of Effects that do not need cleanup are Network requests, Manual DOM mutations, etc.

Sunday, February 21, 2021

React Components Lifecycle

We have learned so far that the React web applications are actually a collection of independent components that run according to the interactions made with them. Each component in React has a life-cycle that you can monitor and change during its three main phases. There are three phases: Mounting, Updating, and Unmounting. You can use life-cycle methods to run a part of code at particular times in the process or application. You can refer to the below diagram to get a visual idea of the life-cycle methods and their interactions in each phase.

Mounting

Mounting is the phase when the component is mounted on the DOM and then rendered on the webpage. We call these methods in the following order when an element is being created and inserted into the DOM:

  • componentWillMount()
  • render()
  • componentDidMount()

componentWillMount(): This function is called right before we mount the component on the DOM. So after this method executes, the component gets mounted on the DOM. It executes this method before the first render of the React application. So all the tasks that have to be done before the component mounts are defined in this method.

render(): This function mounts the component on the browser. 

componentDidMount(): We invoke this function right after the component is mounted on the DOM i.e., this function gets called once after the render() function is executed for the first time. Generally, in React applications, we do the API calls within this method.


Updating

We call the methods in this phase whenever State or Props in a component get updated. This allows the React application to “react” to user inputs, such as clicks and pressing keys on the keyboard, and ultimately create a responsive web user interface. These methods are called in the following order to carry on the update of the component:

  • componentWillReceiveProps()
  • setState()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

componentWillRecieveProps(): We call This function before a component gets its props reassigned. 

setState(): This function can be called explicitly at any moment. This function is used to update the state of a component.

shouldComponentUpdate(): This function is called before rendering a component and tells React whether it should update the component on receiving new props or state. It takes the new Props and new State as the arguments and returns whether or not to re-render the component by returning either True or False.

componentWillUpdate(): This function is called once before the render() function is executed after the update of State or Props.

render(): The component gets rendered when this function is called.

componentDidUpdate(): This function is called once after the render() function is executed after the update of State or Props.


Unmounting

This is the last phase of the life-cycle of the component where the component is unmounted from the DOM. This phase has only one method:

componentWillUnmount(): This function is called once before we remove the component from the page and this marks the end of the life-cycle.

Now that we are familiar with all the life-cycle methods of React components, let us now look at an example to see how each function is implemented in the application code: 

DisplayCycle.js

import React from "react";
import DisplayChild from "./DisplayChild";

class DisplayCycle extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "Pankaj" };
    console.log("Constructor");
  }
  componentWillMount() {
    console.log("componentWillMount Parent");
  }
  componentDidMount() {
    console.log("componentDidMount Parent");
  }
  shouldComponentUpdate() {
    console.log("shouldComponentUpdate parent");
    return true;
  }
  componentWillUpdate() {
    console.log("componentWillUpdate() called");
  }

  componentDidUpdate() {
    console.log("componentDidUpdate() called");
  }
  componentWillUnmount() {
    console.log("componentWillUnmount() called");
  }
  switchState = () => {
    this.setState({ name: "pankaj Kapoor" });
  };
  render() {
    console.log("render Parent");
    return (
      <div>
        <input type="text" value={this.state.name} />
        <DisplayChild firstname={this.state.name} />
        <button onClick={this.switchState}>Click Me</button>
      </div>
    );
  }
}

export default DisplayCycle;

Output:




Saturday, February 20, 2021

React State

Props are pieces of data passed into a child component from the parent while state is data controlled within a component 

What is State?

The state is an updatable structure that is used to contain data or information about the component. The state in a component can change over time. The change in state over time can happen as a response to user action or system event. A component with the state is known as stateful components. It is the heart of the react component which determines the behavior of the component and how it will render. They are also responsible for making a component dynamic and interactive.

Here is an example showing how to use state:

import React, { Component } from "react";
class Test extends React.Component {
  constructor() {
    super();
    this.state = {
      id: 1,
      name: "Pankaj",
    };
  }

  render() {
    return (
      <div>
        <p>{this.state.id}</p>
        <p>{this.state.name}</p>
      </div>
    );
  }
}
export default Test;


Update a component’s state

State should not be modified directly, but it can be modified with a special method called setState( ).

this.state.id = "2021"// wrong
this.setState({         // correct
    id: "2021"

}); 

 

What happens when state changes? OK, why must we use setState( )?  

A change in the state happens based on user-input, triggering an event, and so on. Also, React components (with state) are rendered based on the data in the state. State holds the initial information. So when state changes, React gets informed and immediately re-renders the DOM – not the whole DOM, but only the component with the updated state. This is one of the reasons why React is fast. 

And how does React get notified? You guessed it: with setState( ). The setState( ) method triggers the re-rendering process for the updated parts. React gets informed, knows which part(s) to change, and does it quickly without re-rendering the whole DOM. 

In summary, there are 2 important points we need to pay attention to when using state:

  1. State shouldn’t be modified directly – the setState( ) should be used
  2. State affects the performance of your app, and therefore it shouldn’t be used unnecessarily

 

Important:  Can I use state in every component?

Another important question you might ask about state is where exactly we can use it. In the early days, state could only be used in class components, not in functional components.

That’s why functional components were also known as stateless components. However, after the introduction of React Hooks, state can now be used both in class and functional components.

If your project is not using React Hooks, then you can only use state in class components.

Example 

Test.js

import React, { Component } from "react";
class Test extends React.Component {
  constructor() {
    super();

    // Define your state object here
    this.state = {
      id: 1,
      name: "Pankaj",
    };
  }

  //Event Handler
  upDate = () => {
    // setState() that update state of component
    this.setState({
      id: 10,
      name: "Sachin",
    });
  };

  // Define your render method here
  render() {
    return (
      <div>
        <p>{this.state.id}</p>
        <p>{this.state.name}</p>
        <button onClick={this.upDate}>Click me</button>
      </div>
    );
  }
}
export default Test;

Output:



Differences between props and state

 Finally, let’s recap and see the main differences between props and state:

  • Components receive data from outside with props, whereas they can create and manage their own data with state
  • Props are used to pass data, whereas state is for managing data
  • Data from props is read-only, and cannot be modified by a component that is receiving it from outside
  • State data can be modified by its own component, but is private (cannot be accessed from outside)
  • Props can only be passed from parent component to child (unidirectional flow)
  • Modifying state should happen with the setState ( ) method

Tuesday, February 16, 2021

React Props

Props are an optional input, and can be used to send data to the component. Props are a way of making components easily and dynamically customizable. It’s important to note that props are read-only and that a component must never modify the props passed to it. This also makes them come in handy when you want to display fixed values.

Now that you know about props, make use of them in the components that we have just created with a custom name appended to it.

Make changes to the code between the script tags in your App.js  document to make it look like this:

import MyComponent1 from "./MyComponent1";
import MyComponent2 from "./MyComponent2";

function App() {
  return (
    <div className="App">
      <MyComponent1 name="Beta-Labs" />
      <MyComponent2 name="Beta-Labs" />
    </div>
  );
}
export default App;


This renders the text “Beta-Labs” to the screen. Go ahead and play around with this by switching out the name for yours. Using props added some new syntax to your app.

 

Using Props with Function Components

1.    An argument (props) is passed to the functional component. Recall that since a single argument is being passed to function. Passing this argument lets the component know to expect some data to be passed to it.

2. Within MyComponent1.jsx, the name you want rendered to the screen is passed in by specifying {props.propValue} within the component’s tag.

3.    In the h3 tag, {} are used to print the name that is added to the props object when it’s passed in via the component’s tag. Notice that the name attribute is accessed using the dot syntax.


There is no limit to how many props can be supplied to a component. Now Make changes to the code of MyComponent1.jsx to pass props to the class component:


MyComponent1.js

 

import React from "react";
function MyComponent1(props) {
  return (
    <div>
      <h1>This is Function Component </h1>
      <h3>created by: {props.name}</h3>
    </div>
  );
}
export default MyComponent1;

 

Using Props with Class Components

Adding props to class components is a very similar process to the one used in the functional component above. There are three notable changes:

1.    Props is not passed as an argument to the class

2.    The name attribute is accessed using this.props.name instead of props.name

3.  To pass props to the class component, We just define the normal constructor function (which receives a props object) and call the super method to honour the inheritance of the component.

Now Make changes to the code of MyComponent2.jsx to pass props to the class component:


MyComponent2.js

import React from "react";

class MyComponent2 extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>This is Class Component </h1>
        <h3>created By: {this.props.name}</h3>
      </div>
    );
  }
}
export default MyComponent2;