Header Responsive Ads

What is React Hook

hooks in react

All lifecycle methods, we have learnt in previous lesson, are used to create and monitor changes in state and other variables. Remember that these methods can be used in class component only. Now the question is that how to do state management in function component?

To achieve these features in function component, react add Hooks in version 16.8. Hooks are functions that let you to create state and achieve lifecycle features from function component.

Types of Hook

There are two types of Hooks, react built-in hooks and custom hooks. Most useful built-in hooks are useState and useEffect.

Before calling hook to create state, we should know rules of hooks.

Hook Rules

There are four rules of hooks

  • Call hooks in react function at top level. Calling hooks inside loops, statements or nested functions are not allowed.
  • You can call hooks from react functions or from custom hooks. Calling hooks from regular javascript functions are now allowed.
  • The order in which hooks are called is ensured by react each time a component is rendered.
  • You cannot call hooks inside a class component.

useState hook

useState react hook is called inside react function component to create state. We can pass argument which is used to initialize state value. useState hook returns an array with two items, the current state value and a function which is used to change state value. Follow few simple steps to declare and use state by calling reactjs useState hook.

Declaring State

Import useState hook at the top as

import { useState } from 'react';

Inside react function component, call useState hook. This hook returns an array so you can access array elements by square bracket. Here number is state variable and setNumber is function to change state value.

const App = () => {
  const numberStateVar = useState(1);
  const number = numberStateVar[0];
  const setNumber = numberStateVar[1];
}

Simple way is Array Destructring javascript. Below, we declare destructure array directly containing two items inside square bracket. 

const App = () => {
  const [number, setNumber= useState(1);
}

Accessing State

You can access state variable directly by its name enclosed with curly braces. No need to use this.state here as below.

const App = () => {
  const [number, setNumber= useState(1);
  return(
    <h1>Number is {number}</h1>
  );
}

Output: Number is 1

Updating State

You can update state by calling function returned by useState hook as second items. In this example, it is setNumber. Below on button click, click event handler call setNumber to increase number by 1 on each click.

const App = () => {
  const [number, setNumber= useState(1);
  const handleHandle = () => {
    setNumber(number + 1);
  }
  return(
    <div>
      <h1>Number is {number}</h1>
      <button onClick={handleHandle}>
        Increase Number
      </button>
    </div>  
  );
}

Output: Number is 1

Every time button is clicked, value is increased by 1


Custom Hook

When multiple functions want to use same logic, you can extract that logic into a separate function. You can write custom hook to cover wide range of use cases like timers, animation, form handling etc. Custom hook is created when we have to re-use the code sharing by many components.

Creating Custom React Hooks

Create a new file CustomHook.jsx. Import useState Hook as


import {useState} from 'react';

Write custom hook "useCustomHook". Name of custom hook always start with "use".

import useCustomHook from './CustomHook';
}

Create state and event handler to update state as

const useCustomHook = () => {
    const [count, setCount= useState(0);
    const handleIncrement = () => {
        setCount(count + 1);
    };
}

Return state and click event handler as

const useCustomHook = () => {
    const [count, setCount= useState(0);
    const handleIncrement = () => {
        setCount(count + 1);
    };
    return{
        count,
        handleIncrement
    };
}

Now use this custom hook in App.jsx file as

import useCustomHook from './CustomHook';

const App = () => {

  const data = useCustomHook();

  return(
    <div>
      <h1>Number is {data.count}</h1>
      <button onClick={data.handleIncrement}>
        Increase Number
      </button>
    </div>  
 );

}

You can re-use custom hook as below, we have created two states by calling custom hook.

const App = () => {
  const data = useCustomHook();
  const data1 = useCustomHook();
  return(
    <div>
      <h1>Number is {data.count}</h1>
      <button onClick={data.handleIncrement}>
        Increase Number
      </button>
      <h1>Number1 is {data1.count}</h1>
      <button onClick={data1.handleIncrement}>
        Increase Number1
      </button>
    </div>
  );
}

Output in browser


You can see that both states are isolated and value of each state is increased independently.


useEffect Hook

This hook provide a single API to achieve functionalities of three lifecycle methods, componentDidMount, componentDidUpdate and componentWillUnmount. By default, it is called after every render, including the first render. So you can monitor state, props and other variables. Below is a simple example of useEffect in which we have a state variable number which is being monitored using useEffect hook.  useEffect is called on after first render and after every re-render when number is changed.

const App = () => {
  const [number, setNumber= useState(0);
  
  useEffect(() => {
    console.log('Number is '+number);
  });
  return(
    <div>
      <h1>Number is {number}</h1>
      <button onClick={() => 
        setNumber(number +1)}>
          Increase Number
      </button>
    </div
  );
}

useEffect hook may take two parameters

  • First parameter is a function to monitor state or props
  • Second parameter is an array containing all state variables you want to monitor. It reduces the overhead of calling useEffect for every state variable.

For example, we create three state variables num1, num2, num3 and monitor num1 and num3. It means that useEffect will not be called for num2.

const App = () => {
  const [num1, setNum1= useState(0);
  const [num2, setNum2= useState(0);
  const [num3, setNum3= useState(0);
  
  useEffect(() => {
    console.log('useEffect is called');
  },[num1,num3]);
  
  return(
    <div>
      <h1>Num1 is {num1}</h1>
      <button onClick={() => 
        setNum1(num1 +1)}>
          Increase Number
      </button>
      <h1>Num2 is {num2}</h1>
      <button onClick={() => 
        setNum2(num2 +1)}>
          Increase Number
      </button>
      <h1>Num3 is {num3}</h1>
      <button onClick={() => 
        setNum3(num3 +1)}>
          Increase Number
      </button>
    </div
  );
}

There are few more less commonly used hooks like useContext, useReducer.


Post a Comment

Previous Post Next Post

In Article Ads 1 Before Post

In Article Ads 2 After Post