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

Nihar Raote
Level Up Coding
Published in
3 min readSep 4, 2022
Photo by Lautaro Andreani on Unsplash

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:

A regular function and a custom React hook prefixed with the word use.
A regular function vs a custom React 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.

A simple example of a custom React hook.
An 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.

Originally published on my blog.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Written by Nihar Raote

Front-end developer. Self learning programmmer. Currently learning web development. Also interested in web design

No responses yet

What are your thoughts?