Table of contents
1.
Introduction
2.
State Hooks 
3.
Effect Hooks
4.
Rules of Hooks
5.
Build your Custom Hooks
6.
Built-in Hooks
7.
Advantages of Hooks
8.
Frequently Asked Questions
9.
Key Takeaways
Last Updated: Mar 27, 2024

Hooks at glance

Author Rubleen Kaur
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81.  Hooks allow us to use the functionality of various states and React features without using the class. So what do we mean by that? Using Hooks will enable you to create an entire React Application with just functional components. Yes, that is right! No more classes are required in a React application. An important point to remember is that Hooks do not work inside a course. Hooks are known to be backward compatible, which means that they do not contain any breaking changes.

 

 

Let’s see how we can create a component using a Hook in ReactJs.

 

import React, { useState } from "react";
export default () => {
  const [text, setText] = useState("");
  return (
    <input
      value={text}
      onChange={(e) => {
        setText(e.target.value);
      }}
    />
  );
};

 

The above code is a simple example of how we can create a react hook. Moving on, now we have seen what hooks are and an example related to them. Well, there is much more to it. Let’s take a look at the bare hooks and their models.

State Hooks 

Hooks state allows you to declare a state in the React App. The React useState uses this hook to return a current state’s value pair and the function to edit or update the value. We can make a call to this function from an event handler or from anywhere else. The ReactJs offers something similar to this.setState in a class, except the hook does not merge the old and the new state after any updates. 

Note: We can use the state hooks more than once in a single component. 

 

Let’s go through an example, to understand better:

 

import React, { useState } from "react";

function CountNinja() {
 // Declaring a new state variable.
 const [count, setCount] = useState(0);

 return (
  <div>
    <p>Ninja clicked {count} times</p>
    <button onClick={() => setCount(count + 1)}>Click me</button>
  </div>
);
}
export default CountNinja;

 

 

 

Using the above code, if I press the button two times, the output on the application is shown as Ninja clicked two times. 

The useState Hook in React declares a state variable. It is used to preserve values between the function calls; as we can observe in the above example, we have taken count as a state variable, but we can name it anything per our choice. 

We have a separate detailed article about the State Hooks. Want to learn more about it?
We have got you covered, Do give the ‘Using the State Hook’ article. 

Effect Hooks

Besides the bare- useState hook, we have useEffect hook that is another “Core React Hook.” 

useEffect() considers a function observing input and returns nothing; it runs additional code after render. We can see it as a combination of React Component lifecycle methods: componentDidMountcomponentDidUpdate, and componentWillUnmount. Using Effect Hooks, we can add listeners after the component has been rendered.

If needed, we can use the hook effect to return a function which is a cleanup function. The function is used to perform cleanups, e.g., to prevent the introduction of memory leaks. Results have three standard features which most web applications require:

  1. To update the DOM.
  2. To fetch and consume data from the API.
  3. To set up a subscription, etc. 

Let’s go through an example to understand the React Hooks better:

 

import React, { useState, useEffect } from "react";

const App = () => {
 const [message, setMessage] = useState("Hi Ninja, how are you?");

useEffect(() => {
  console.log("This is a trigger use effect hook");

  setTimeout(() => {
    setMessage("We hope you are doing great! Bye :)");
  }, 2000);
});

 return <h1>{message}</h1>;
};

export default App;

 

OUTPUT

 

 

In the example, we have used the useEffect to trigger the setMessage method, which changes the message variable after a second. There is a slight problem with the component, and we can see that the console.log statement is triggered twice. The useEffect hook by default starts the DOM on any change in either state or prompt. We can overcome this problem by passing an Empty arr[] as the second argument above. 

In React Components, we have two types of side effects:

  1. Effects without a cleanup
  2. Effects with a cleanup.

 

Effects without a CleanUp

 

Effects without cleanup are used in useEffect, so it does not block the browser from updating the screen. This makes our app more responsive. The most common effects that don't require a cleanup are manual DOM mutations, Network requests, Logging, etc.

All the examples we have discussed till now are effects that do not require cleanup. 

 

Effects with a CleanUp

 

Some effects require cleanup after the DOM update. For example, if we want to set up a subscription for some external data source, it is essential to clean up memory to avoid a memory leak. React performs the cleanup of memory when the component unmounts. The effects run for every render method and not just once. Therefore, React also cleans up effects from the previous render before running the effects next time.

 

For example, 

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import fetch from "./fake-fetch";

function Employees() {
 const [list, setList] = useState(null);

useEffect(() => {
  let controller = new AbortController();
  (async () => {
    try {
      const response = await fetch("/employees/list", {
        signal: controller.signal
      });
      setList(await response.json());
      controller = null;
    } catch (e) {
      // Handle fetch error.
    }
  })();
  return () => controller?.abort();
}, []);

 return (
  <div className="list">
    {list === null ? "Fetching employees..." : null}
    {list?.map((name) => (
      <div className="item" key={name}>
        {name}
      </div>
    ))}
  </div>
);
}

function About() {
 return (
  <div className="about">
    <p>Coding Ninjas provides the best curated content.</p>
    <p>Happy Learning Ninjas!</p>
  </div>
);
}

function App() {
 const [page, setPage] = useState("employees");

 const showEmployeesPage = () => setPage("employees");
 const showAboutPage = () => setPage("about");

 return (
  <div className="App">
    <h2>Ninja List</h2>
    <a href="#" onClick={showEmployeesPage}>
      Ninjas List
    </a>
    &nbsp;
    <a href="#" onClick={showAboutPage}>
      About Us
    </a>
    {page === "employees" ? <Employees /> : <About />}
  </div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

 

OUTPUT

 

 

 

The Effect Hook unifies both the use cases by using a single API reference.

 

Rules of Hooks

Few Rules we should keep in mind when either creating our hooks and even using the built-in hooks are: 

  1. Hooks should be called from the top of the level. 
  2. Hooks should be called from the React functions.

These are the two main rules you should keep in mind before you create or use Hooks. 

 

Build your Custom Hooks

Custom hooks are general essential functions with the keyword “use” before their identifier.  The customized hook is just like a regular function, and the word "use" in the beginning tells us that this function follows the rules of Hooks. Building custom Hooks allows us to extract component logic into reusable parts.

Let’s try to create our custom hook to understand it better. 

 

import React, { useState, useEffect } from "react";

const useNinja = (title) => {
useEffect(() => {
  document.title = title;
}, [title]);
};

function CustomCounter() {
 const [count, setCount] = useState(0);
 const incrementCount = () => setCount(count + 1);
useNinja(`Ninja clicked ${count} times`);

 return (
  <div>
    <p>Ninja clicked {count} times</p>
    <button onClick={incrementCount}>Click me</button>
  </div>
);
}
export default CustomCounter;

 

 

OUTPUT

 

We have a separate blog that has covered how to build your custom hooks in detail, do give it a read.

Built-in Hooks

The few Hooks we have discussed are known as Basic Hooks; well, there is more to it!

We have many Built-In Hooks which reactjs to offers. The Built-In Hooks are generally divided into two parts:

  1. Basic Hooks:
  • useState
  • useEffect
  • useContext

     
  1. Additional Hooks:
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

Advantages of Hooks

React Hooks allows us to attach the functional components to the local state. This is how we can use the functionality of React without the class component. 

Few Advantages of Hooks are: 

  1. It makes the code more readable. 
  2. It reduces the code length.
  3. Overall optimization of the components is improved.
  4. We can write a functional component with a state. 
  5. It makes complex writing components much more accessible. 
  6. It handles the events and logic in the available components. 
  7. It boosts the performance with the use of functional components. 

     

In the above article, we have covered all basics of using ReactJs hooks, and now we have a small set of curated questions most of the developers have about Hooks.

Frequently Asked Questions

  1. What are React Hooks?

    Ans: Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81. Hooks allow us to use the functionality of various states and React features without using the class. Hooks allow you to create an entire React Application with just functional components.

     
  2. Is useState hook asynchronous?

    Ans: useState and setState both are asynchronous. These hooks do not update the state immediately but have queues that are used to update the state object. This is used for improving the performance of the rendering of React components.

     
  3. Why is React Hooks better?

    Ans: Using Hooks, we can extract stateful logic from a component that can be tested solely and reused. Hooks allow us to reuse the stateful logic without changing our component hierarchy. This makes it easy to share Hooks among many components or with the community. 

Key Takeaways

Hey everyone, so let’s brief out the article. Let’s discuss in brief whatever we have discussed here. 

  • Hooks in React allows you to hook into the react state and lifestyle features through the function component. Hooks are a new feature update of the React in version 16.81. Hooks allow us to use the functionality of various states and React features without using the class.
  • After discussing the basics of hooks, we have gone over each type of hook using an example, and the fantastic feature is that you can create your custom Hooks by just using the “use” keyword before declaring a function.
  • The article then covers the advantages of using Hooks and the most frequently asked questions from the developers about Hooks. 

 

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

 

Happy Learning Ninjas!

 

By: Rubleen Kaur

 

Live masterclass