Nihar's Dev Corner

Custom React Hooks. What are they and how are they helpful?


Introduction

React Hooks were introduced in React.js v16.8. They allow us to use state in functional components, similar to the lifecycle hooks of class-based components. For every situation, there is a React Hook you can use. From the frequently used hooks like useState and useEffect to hooks like useCallback and useMemo, you can take your time to browse the documentation for the hook you need.

Since there are hooks for almost every situation you might encounter, is there a need for your own React Hook?

What are custom hooks?

When we want to re-use some logic in multiple places, we extract it to a function. If we also want to re-use some JSX along with it, we extract it to a separate component. Similarly, a React Hook is also a function.

If we want to create a reusable function that also uses React Hooks like useState and useEffect, we cannot store this logic in a plain function.

A component can be created to store this reusable logic so we can then use hooks. But this is not ideal if we do not have any JSX to write in that component.

In such situations, the reusable logic can be extracted to a custom React Hook. Making a custom React Hook is simple - prefix a function's name with use. For example:

Regular function vs a custom hook

An example of a custom hook

Here is some logic that has been extracted into a custom hook.

The custom hook useSelectClub takes an array of sports clubs as an argument. A person can belong to one or more sports clubs. If a club is marked as a person's favorite, then that club's code is returned. If the user belongs to a single club, that club's code is returned.

Example of a custom hook

Wrapping up

I hope this short guide helped you to understand custom hooks in React and how to use them.

Just like how recurring JSX and logic can be turned into reusable components, logic that uses React Hooks can also be turned into reusable custom hooks.