Building Your Own Hooks
What are hooks?
What are custom hooks?
Custom Hooks are method to reuse stateful logics in other components without writing extra code.Like we need a function which has to be used in many components. So instead of defining that function again and again, we will develop our own hook.
Rules of creating customs hooks :-
Whenever we will create a hook, first of all we have to keep in mind that the name of our hook must start with this word “use” and then its name shall begin. Like “useTestHook” and “useCustomHook”
So let's understand with an example
How to create a custom hook :-
In this image above we have developed a custom hook to change the title when the user clicks on the button. So basically, we are developing a function whose name is "useDocumentTitle" and giving it a parameter which is title, inside the hook we are using “useEffect” hook to change our page title when the title variable is changed.
When the user clicks on the Increment button then the title and the number will increase to 1.
Custom Hooks offer the flexibility of sharing logic that wasn’t possible in React components before. You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and probably many more we haven’t considered. What’s more, you can build Hooks that are just as easy to use as React’s built-in features.
Try to resist adding abstraction too early. Now that function components can do more, it’s likely that the average function component in your codebase will become longer. This is normal — don’t feel like you have to immediately split it into Hooks. But we also encourage you to start spotting cases where a custom Hook could hide complex logic behind a simple interface, or help untangle a messy component.
Leave a Comments