If you have been using React for a while, chances are you have come across the need to extract some logic into a reusable function. And with React hooks coming into the picture, doing this has become a walk in the park. We can write our own custom react hooks to abstract complex logic in a function and reuse it across components.

What is a custom React Hook?

A custom React hook is really a function that runs inside of a component. It can run other hooks or other functions inside it. These functions/hooks can be recursive too. It makes patterns like render props and higher-order components unnecessary. It is a powerful tool to have in your arsenal when writing functional components and it provides us with the following advantages:

  • Build your own hook/logic
  • Provide the ability to hook into React specific functionalities such as lifecycle and state
  • Portable logic
  • Rapid iterations

With hooks and custom React hooks in the application, we can start relying on our components to be responsible for the user interface and hooks being the piece that handles business logic.

If you have not dived into React hooks yet, we recommend checking out our previous posts about React hooks before diving into this one.

One thing to know before getting started with custom React hooks is that the function has a naming convention. The logic inside does not matter, but the function must be prefixed with the word “use”.

It is also a good idea to check out the rules of hooks post in the React docs before working with custom hooks.

This post is about understanding and writing custom React hooks, and not about what all is possible using them. The sky is the limit and a lot of the open-source community has already developed an insane number of hooks. Though they might be useful for our applications, we should know how to write our own custom React hooks since our business case related hooks would not exist.





#react-hook #programming #javascript #web-development #react

How To Write Your Own Custom React Hooks
2.00 GEEK