React Hooks tutorials for beginners-14

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.

--

--

--

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Multi-Tenant AWS Amplify

Surveyj.co - Scam, Spam Without Green Eggs, and Ham - Stylecompassmedia

5 key advantages of React Native

The Shop — Luxury Car E-commerce Store

Real Time Analytics Display in JavaScript

Redux and React-Router v4: a Tale of Two Datastores

VIRTUAL INTERNSHIP PROGRAM AT LETSGROWMORE

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
Nabendu Biswas

Nabendu Biswas

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger

More from Medium

3 React Hooks You Should Not Miss in 2022

How to make a table in React with Hooks

Best Practices for Writing React Components

State Management and React