Welcome to part-14 of the series. You can find part-13 here. We will continue learning to make custom hooks in this part.
We will create a new custom hook now. We are going to create a hook, useCounter which will help us to reuse the logic of a simple counter. But let’s first make the counter code.
Create a new file CounterOne.js inside the components folder. Here, we have a simple counter, which have increment, decrement and reset functionality.
Suppose, we want similar functionality again. So, we will create another file CounterTwo.js inside the components folder, with same content.
Now, we will include both Components in App.js
Now, we have two separate Counters in localhost.
Now, as we are repeating the code, we will avoid it by using custom hooks. Create a new file useCounter.js inside the hooks folder and put the below content in it.
We are moving all of the state and increment, decrement logic to this file. We are also returning count, increment, decrement, reset in an array.
Now, back to CounterOne.js we can use count, increment, decrement, reset by array destructuring.
We will refactor our CounterTwo.js also in the same way.
Back to localhost our app, will work similarly.
Hooks also provides a great deal of flexibility. We can change our initial count value in the hook. We are now passing an initialCount as a paramater, with default value of 0. Also, in the useState passing the initialCount and also passing it in reset.
Now, we will not pass anything in CounterOne.js, so it will take the default value of 0. But in CounterTwo.js , we are passing the value of 15.
Now, in localhost if we come we can see the initial count for counter two is 15.
This completes part-14 of the series and completes our Hooks series.
You can find the code for the same in this github repo.