Tuesday, May 19, 2020

ReactJS Hooks

ReactJS Hooks


Hooks were added and introduced in React 16.8. We can use state and other React features without composing a class. Hooks enable us to make use of these features in functional ReactJS components. Hooks allow us to attach ReactJS state and lifecycle features from function components and we can use more React’s features without using classes. 

We need to understand a few things about hooks before moving ahead, 

  • Hooks are optional. If you don’t want to learn or use Hooks you can skip them.
  • Hooks are fully backward-compatible. Hooks don’t hold any breaking changes.
  • They are not there to remove classes from React.
  • You do not need to update or replace your existing knowledge about React concepts.
  • You can gradually adopt hooks in your programming practice.

To understand hooks, let us take a simple component that generates a random integer number between 0 to 9 on every button click.

class RandomComp extends React.Component
    const num=Math.floor(Math.random() * 10);
    return <div><button onClick={this.updateNumber}>

Conventionally, this can not be done using a functional component, but we can create a component using a function with a state hook.

The same component can be written using the state hook as,

function RandomComp() {
  const [number, getRandom] = useState(0);
  var num=()=>Math.floor(Math.random() * 10);
  return (<div>
      <button onClick={() => getRandom(num)}>Random</button>

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

There are few drawbacks associated with class components; those are discussed in this article. More streamlined, smaller, and focused components can be designed with functions.

The useState() method uses a destructuring assignment for arrays.

const [number, getRandom] = useState(0);

  • The first variable is the state value
  • The second variable is a function to update the state value 
  • The useState methods argument is the initial state value

Another example,

function RandomComp(props) {
   const imagearr=props.images;
   const len=imagearr.length;
  const [current, getNum] = useState(0);//Hook
  return (<div>
      <button onClick={() => getNum(Math.abs((current-1)%len))}>Prev</button>
      <img src={imagearr[current]} alt='unable to load'/>
      <button onClick={() => getNum(Math.abs((current+1)%len))}>Next</button>
//Image url array
const srcs=[
ReactDOM.render(<RandomComp images={srcs} />,document.getElementById('root'));

the result will appear as,

reactjs hooks

Multiple state hooks

Multiple state hooks can be used in the same way. For example,

import React, { useState } from 'react';

function AllTheThings() {
  const [count, setCount] = useState(0);
  const [volume, setSize] = useState(null);
  const [item, setItem] = 
     useState([{ itemName: 'Cynlinder', ht: 100 , wd : 44}]);

  return <div>{/_ use all those things here _/}</div>;

The Effect hook

The state hook is used to maintain the component state. The next thing functional components need to have to compete with class components is the life cycle methods. The Effect hooks are similar to componentDidMount, componentDidUpdate, and componentWillUnmount. The effect hooks can be used to do things like fetching the data, changing the DOM (document title) manually, and setting up a subscription.

For example, a Timer component can be created, that will be updated after each second to display current time and date.

function Timer(props) {
    const t=new Date().toLocaleString();
    const[time, setTime]=useState(t);
    useEffect(() => {
      setInterval(() => {
        setTime(() => new Date().toLocaleString() );
      }, 1000);
    return <div><h2>{time}</h2></div>;

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

The useEffect() method will transmit the effects in the time variable after each second and the time will be updated on the screen.