React Hooks tutorials for beginners-14

Image for post
Image for post
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.

Image for post
Image for post
CounterOne.js

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

Image for post
Image for post
CounterTwo.js

Now, we will include both Components in App.js

Image for post
Image for post
App.js

Now, we have two separate Counters in localhost.

Image for post
Image for post
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.

Image for post
Image for post
useCounter.js

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

Image for post
Image for post
CounterOne.js

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

Image for post
Image for post
CounterTwo.js

Back to localhost our app, will work similarly.

Image for post
Image for post
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.

Image for post
Image for post
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.

Image for post
Image for post
CounterTwo.js

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

Image for post
Image for post
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.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store