Hooks are used in React to manage states and other features without class components. It can be used to separate the logic from the code to make it simpler and available to reuse across the components.

Some commonly used React Hooks are useState, useEffect, useContext which serves different purposes. In this way, we can create our own hooks for different use cases and that are called as custom hooks.

Rules in creating Custom Hooks:

There are certain rules to be followed while creating custom hooks. They are:

  1. Hooks must start with ‘use’ keyword.
  2. Hooks can be called only at the top level and not inside any loop or conditions.
  3. Hooks can be called only inside functional components.

Other available hooks like useEffect, useState or any other can be used inside custom hooks.

Example:

Lets discuss the concept with the following illustration. Here, the component fetches user Data without any custom hook.

The problem here is, when multiple components need to fetch and use this user Data, this have to be duplicated. So, to avoid redundant code and to separate business logic from UI, we can replace this with custom hooks as given below.

Create a custom hook as “useUserData.js”

Now use this hook in any component that needs to fetch user Data.

Hence, whenever we need to use similar logic like fetching, authentication in multiple components and to make the code simpler or reusable, we can create and use custom hooks.

Leave a Reply