Here’s WHY Custom Hooks ARE AMAZING!

Vikram Nayyar CS
2 min readMay 28, 2024

--

Introduction:

In this week’s blog post, we’re talking about custom hook’s in React JS. I never used to understand them although recently, I’ve been able to integrate them into a recent web app that I’ve been developing.

Read on further to learn more about hooks in React as well as a few examples that I’ve been able to create.

As always, before we get into the blog post, please make sure to applaud, comment and share with your friends.

Happy Reading!

So What is a Hook in React?

The simplest definition is a function that can only be used within Functional Components in React that performs a particular bit of logic, that conforms to “The Rules of React Hooks”.

Rules:

React relies on the order in which hooks are stated (this should not change).

Hooks can only be called inside React components.

Hooks cannot be conditional.

Examples:

useState — Essentially handles a variable in React. Returns the variable and a setter function.

useEffect — Takes in a piece of code that runs once on the initial render and again based on the dependencies in an [].

useMemo — A hook that handles the rendering of a component (aiming to optimise performance).

You can tell by now that they all start with ‘use’

What is a Custom Hook?

It’s a piece of code that conforms to the rules above that the programmer develops for a particular purpose.

Why I Like Them?

They allow me to abstract away logic into a separate function & file.

I can then pull them in easily using JavaScripts destructuring syntax (with [] or {}).

Examples Where I’ve Made Use of Them:

Pulling in data — Pulling it in from the database in one place so that it can be used across the application.

Data Formatting — Handling this logic in an external file (the hook). Then pulling it in and passing it to child components as props.

Conclusions:

Custom hooks are definitely handy as a developer. I used to be a bit shy with them, not understanding their purpose and the potential of them. Nowadays, I’m creating my own and using other hooks (like useState()) within them.

Final Things:

As always, thank you for taking the time to read this article!

All my links are here!

--

--