DEV Community

Ragul Murugesan
Ragul Murugesan

Posted on

Are you using the custom hooks in React right?

Custom hooks are method that helps us to create and maintain functionalities outside the component that can be re-used and called across various components in the application.
Does it sound familiar? Yes, they are basically util functions that we tend to keep in utils.js when we were working before the hooks storm or before even started using libraries like React or Angular.

Also, this is a proper example for Dependancy Inversion in S.O.L.I.D principles.

Here instead of keeping them as functions in a js file, we are keeping them as hooks that can be called at the top of the component.

Why use custom hook?

As the application grows in size, it is important to abstract the logic outside the component that can be re-used. It helps us to improve modularity of the code. By moving such logics outside, you can keep many Components simply as presentational components.

By creating your own custom hook, you refrain from using an external library to add new functionality thus saving space and maintenance cost.

As custom hooks are meant to be used on top of the component like in-built hooks, you can use useState, useEffect or even custom hooks inside the same.

Points to remember while creating a hook

  • Start with “use” keyword.
  • Keep SOLID principle in the mind — The hook should do only one thing.
  • Define the types before hand for params — If typescript — great.
  • Should be used only at the top of the component where you are consuming
  • Do not add new params or options thinking it might come in the future. Keep room for scaling; when there is a need, we can extend the hook’s capability

For the complete article, please visit medium blog.

Top comments (1)

Collapse
 
ashutosh__ico_074e41d466f profile image
Ashutosh _ico

No never