React Hooks tutorials for beginners-14

Nabendu Biswas
3 min readNov 17, 2020
React Hooks

Welcome to part-14 of the series. You can find part-13 here. We will continue learning to make custom hooks in this part.

Custom hook

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.

CounterOne.js

Suppose, we want similar functionality again. So, we will create another file CounterTwo.js inside the components folder, with same content.

CounterTwo.js

Now, we will include both Components in App.js

App.js

Now, we have two separate Counters in localhost.

Counters

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.

useCounter.js

Now, back to CounterOne.js we can use count, increment, decrement, reset by array destructuring.

CounterOne.js

We will refactor our CounterTwo.js also in the same way.

CounterTwo.js

Back to localhost our app, will work similarly.

Similar app

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.

initialCount

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.

CounterTwo.js

Now, in localhost if we come we can see the initial count for counter two is 15.

Counter

This completes part-14 of the series and completes our Hooks series.

You can find the code for the same in this github repo.

--

--

Nabendu Biswas

Architect, ReactJS & Ecosystem Expert, Youtuber, Blogger