The need for Custom Hooks: The main reason for which you should be using Custom hooks is to maintain the concept of DRY(Don’t Repeat Yourself) in your React apps. For example, suppose you have some logic that makes use of some built-in hooks and you need to use the logic in multiple functional components. So, there are two ways left for you — 1) write the same logic in each and every component (which violates the concept of DRY) and 2) create a separate function that wraps the logic inside it and then call it from those components. The second option is undoubtedly a better choice as you have to write the logic only once. Here, the separate function you created is the custom hook. So, whenever you feel that you have a logic that is to be used in multiple functional components(hooks don’t work in class components), just create a separate custom hook for it and use it.
Using the custom hook in components: To use the custom hook in your components just import the “useCustomHook” function from “useCustomHook.js” file in the “src” folder.
Filename : src/components/SecondComponent.js:
If you open the console of your browser, you will see:
Note that the useEfffect is called after the first render even though we declare the dependency array. That means the callback function passed to the useEffect hook is executed after the first render and when the variables in the dependency array get updated. There is no straight way to prevent this first execution.
Now, if you click the first button(button of the FirstComponent) and check the console, you will see that each time you click on the button, the value of the counter increases by 1, and the updated value is printed on the console.
If you click the second button, it will be similar to the above output, carefully check the console:
Note that both the counters (defined in “usecustomHook”) of the two components are different. The two components use two different “counter” state variable(see “useCustomhook.js”), they don’t share the states. Therefore, in this React app, each component has its own “counter” state variable. Similarly, each component has its own useEffect and they are executed independently of each other. If the counter of the FirstComponent is updated, the useEffect of the FirstComponent is called, similarly if the counter of the SecondComponent is updated, the useEffect of the SecondComponent is called independently of the FirstComponent (See the above output).
In the “src/components/FirstComponent.js” the code is equivalent to the below code:
Note: It is important to name your custom hooks starting with “use”, because without it React can’t realize that it is a custom hook and therefore can’t apply the rules of hooks to it. So, you should name it starting with “use”.