Quick and Easy Steps to Making your Own React Hook

Gabriel Chazanov
2 min readJun 28, 2021
Let’s talk about hooks!

If you’re an amateur React engineer, you should already have some idea of what React hook is. Essentially a React hook is a chunk of reusable logic that can be used to make your life easier, especially when dealing with stateful situations. The useState hook being one of the most popular, allows you to save a variable in state and alter it at will.

Making your own hooks allows you to write DRY code, and feel the sweet thrill of creation.

The first step to creating your own hook is to create a file to hold your reusable logic. Conventionally, this can be held in a directory called lib or utilities or what have you. Once created you will need to set a default export for the file in question using this syntax:

export default useHookInQuestion

While we’re on the topic of syntax there are a few things to note about how to write your hooks. For one thing all hooks should be written in standard JS camel case capitalization. thisIsHowYourWriteAHook. Don’t worry, if you thought it was necessary to capitalize the first letter of the hook as though it were a React component, you're from the only one. Additionally, all hooks should start with the word use before anything else. This convention is there to remind you to follow the two rules of hooks. What exactly are these you ask, dear reader?

The first rule of hooks is to only call them at the top level of a function or component that you are writing. This ensures that all hooks are called in the correct order, a dreadfully important issue when it comes to rendering pages correctly every time. The second rule of hooks is to only call them while inside of a React function. This is an issue of clarity, as React is a stateful version of JS, you want to make sure that all things dealing with state, ie hooks, are nestled where they should be, namely with other React code.

Once you’ve written the logic for your hook, with the appropriate syntax, all that’s left to do is import it into which ever React component you are using it for. Once that’s done, call your custom hook at the very top level, and congratulate yourself, because you’ve created a bona fide custom React hook.

--

--

Gabriel Chazanov

He/Him; Full Stack software developer who’s always striving to learn