What is React hooks API – How to used it?

React Hooks were first introduced in React 16.8, Hooks are functions or reusable functions that let you “hook into” React state and lifecycle features from function components. In React, hooks start with use word, we have hooks like useState, useEffect, useMemo, useContext, useReducer, etc. We can create our own custom hooks and so whenever you start creating your own custom hook, is a convention to start your hook’s name with the use word.

In this tutorial, we’ll have three objectives, first learn what are React hooks, second on discussing on React hooks list available in React and discuss on an important concept in React hooks in details.

React hooks in details
Angular hooks

What are React hooks?

In React we have the privilege to create React Component using function and class-based. Function component codes are cleaner, leaner, and easier to understand, so in the Function component. With introduce of React Hooks, we can almost do what we are doing in the Class component.

In react, hooks are functions or reusable functions that are only called within the function component. We can use React hooks API to perform different activities like managing the state of components using the useState hook, managing application state using useContext, mimicking class component life cycle using useEffect, and more. The React hook can be reused across our application and let you use state and other React features without writing a class.

Stateful function components have cleaner, lesser code, and better organization than class components. In class components, the state of the component is set up in the constructor function, event handlers were bound to this keyword.

React allows us to create our own custom hooks, when different components in our application have the same logic, then we can extract the common code and create reusable React custom hooks.

Note : React function component not only reduce development time and coding, it also reduces production bundle size, by about 60%.So we can take advantage of using hooks in function component.

When to use React Hooks?

Before React 16, Class components are first-class citizens because it has state and life cycle hooks, React function component is just for presentation and dumb and doesn’t have life cycle hooks.

With introduce of React hooks API in React 16.8, we can do almost all things in a function component as we do the in-class components. React useEffect hook allows us to mimic a component’s lifecycle without writing a class component. With React 16 onward, we have useEffect react hooks based on array dependency with three cases, with useEffect, it allows us to mimic the Class component life cycle in React function component.

React function components are preferable to the class components. As functional components are faster, cleaner, and easier to understand, using hooks in function components has the following advantages over class components.

  1. Cleaner and less code, as we don’t need a constructor and super keyword.
  2. No need for this keyword and bind handlers for a simpler lifecycle model.
  3. Code reusability, we can create custom hooks to handle features that are common among many functional components.
  4. Better code organization and easier to manage code.

React Hook Rules

To use hooks in the functional component, we have specific rules to follow as below.

  • Hooks can only be called inside React function components.
  • Hooks cannot be conditional
  • Hooks can call other hooks

React hooks list

React provides us lot of ready-to-used hooks inside our function component. Here we have listed hooks that are available and ready to use.

  1. useState : hooks for stateful function components
  2. useEffect: hook for cleaner side effect management
  3. useContext: hooks for State management or avoid props drilling
  4. useRef
  5. useReducer
  6. useState
  7. useCallback
  8. useMemo
  9. useTransition
  10. useImperativeHandle
  11. useLayoutEffect
  12. useDebugValue

React useState: manage state in Functional Component

The React useState hook is the most used hook and it allows us to track and manage the state in a function component. The state generally refers to data that we used in the component, the data can change over time. So whenever there is a change in state, React should rerender the component to reflect the new state in UI.

Syntax for React useState.

const [name, setName] = useState('Edupala');
setName('Edupala 2022'); //Change to new value

The useState function returns an array with two values, we can use array destructuring to assign it to a value for a variable and function to change its state.

  1. First the data or variable with an initial value
  2. The second value is a function that modifies or updates its value.

Where the name is variable and we have initialized its value ‘Edupala’ through useState, setName is the function’s name to change the name value. The useState() hooks allow functional components for setting and retrieving state. Let us understand Hook’s state with the following example.

In the above example, we have the framework date, we can change or manage its state using useState hooks. We initialized its value with React and can change its value using setFramwork, by calling it any time we change the select input. If you don’t want to assign an initial value then define useState with empty parenthesis.

So whenever there is a change in state variable, react re-render that component to update its UI.

We can use the previous state from useState hooks to generate a new state as follows.

import React, { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>React previous state : { count }</h1>
      <button onClick={() => setCount(prevState => prevState + 1)}>  
        Click me  
      </button>  
    </div>
  );
}

React useEffect Hooks

React useEffect allow us to mimic the class component life cycle inside the function component.

The useEffect Hook allows us to perform side effects in function components. React component’s main job is to return part of the UI, so it can contribute to the overall user interfaces of our application. Sometimes our components reach and perform outside of their scope like interacting with other APIs. An action that impinges on the outside world in some way is called a side effect and we can have the following side effects

The useEffect hook, allow us to perform similar React class lifecycle method like componentDidMount, componentDidUpdate, and componentWillUnmount combined.

The useEffect Hook allows us to perform side effects in function components. React component’s main job is to return part of the UI, so it can contribute to the overall user interfaces of our application. Sometimes our components reach and perform outside of their scope like interacting with other APIs. An action that impinges on the outside world in some way is called a side effect and we can have side effects.

  1. Calling asynchronous API calls for data
  2. Working with setInterval or setTimeout
  3. Updating DOM element manually.
  4. Updating global variables from inside a function.
  5. Setting or getting values in local storage

The useEffect allow us to better control the side effect that introduces in our react component.

React useEffect syntax

React useEffect accept two arguments.

useEffect(<function>, <dependency>)

The first argument is a function that executes when useEffect hook is executed, the second argument is a dependency array. Based on dependency we can control when to execute useEffect, we can have the following value to dependence cases.

  1. When dependency array is empty array [], useEffect hook run only once during component initial render.
  2. When the dependency array is not specified or has no value, then the useEffect hook runs during the component’s initial render and every time the component rerenders.
  3. When dependency array with [data] or [data1, data2] the useEffect hook runs during initial component renders, and every time data or value in dependency changes.
import { useEffect, useState } from "react";
import "./form.css";

const Example1 = () => {
  const [framework, setFramwork] = useState("React");

  useEffect(() => {  // Case 1
    console.log("Run only one times");
  }, []);

  useEffect(() => { // Case 2
    console.log("Run on every time component rerender");
  });

  useEffect(() => { // Case 3
    console.log("Run every time dependency value change");
  }, [framework]);

  const onSubmit = (data, event) => {
    console.log(data);
    event.target.reset();
  };

  return (
    <div className="formInput">
      <label>Frontend framusework</label>
      <select
        className="form-select"
        onChange={(e) => setFramwork(e.target.value)}
      >
        <option value="Angular">Angular</option>
        <option value="React">React</option>
        <option value="Vue">Vue</option>
      </select>
    </div>
  );
};

export default Example1;

Case 1: Run only time during component mount or initialize.
Case 2: Run on every time component rerender.
Case 3: Run only when framework value change, or dependence value change.


Conclusion: In this tutorial, we have learned what is the hook, and how hooks allow us to do multiple things that we can do in class components like state management, component life cycle hooks, and more. Hooks are javascript functions, that we can reuse across our application.

Related Articles

  1. When and how to use React Context API in react 18?
  2. React router navigates outside components.
  3. How to implement React routing using react-router-dom?
  4. What is react-redux – an example in React?
Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top