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.