React provides many in-built hooks that you can use in your app
But you can also create custom hooks, which helps reduce the amount of code
Custom hooks are similar to functions but usually start with use and may call other in-build hooks as well
Need for Custom Hooks
The main reason why you should be using Custom hooks is to maintain the concept of DRY(Don't Repeat Yourself)
To understand more about DRY and WET refer to the tweet below.
When and How to use it
If you want to share the logic between different components, we can extract that to a separate function.
Because custom hooks are JS functions the rules of hooks apply to it as well.
Rules of Hooks are-
Never call Hooks from inside a loop or condition
Hooks should sit at the top-level of your component
Only call Hooks from React functional components
Never call a Hook from a regular function
Hooks can call other Hooks
Building your Custom Hook
Making your own hook is similar to making a JavaScript function, but its name starts with use.
Inside them, you can use any other hook, take anything as parameters, return anything you want it to return.
Put it to the test
Let us create a custom hook that uses useEffect hook that updates the title of the document
This is how you traditionally write the code
Creating the custom hook
What we would do is take out the incrementCount function and put it in a separate file and pass the count state in it.
Like this
Call the Custom hook
Call the hook in your file as you would normally call a JS function
Conclusion
This is how easy it is to make your own custom hooks and integrate them into your application
If you want to try and experiment with this code, here is the link to the same
Top comments (0)