How to Create Your First React Hook (Counter With Increment and Decrement)

In the last article, we have seen how to create a component in React. Now let’s make that react component stateful using React Hooks. There is a number of React’s hooks out there but we will be starting with a very basic one that is React.useState().

Note: This will be a continuation of the last article for which we have given link above. We suggest you go through it and set up all the things. Our upcoming articles too will depend on our previous articles.

We are using 3 buttons. Reset, + (to increment) and (to decrement).

Step 1: Make Changes In App.Js File

Add the following button counter component in the App.Js file. Before that remove the Hello component which we have created in the last article.

App.Js



In the above Js file, In the ButtonCounter() component we are setting initialState value to 0. Passing React.useState() initialState value. Hook useState() returns two values which is state value (count) and setCount function which is used to upadte value of count.

Next, we are displaying a count value.

After that, we are calling setCount function using an arrow function technique on button click events. The first button (Reset) will always use intialState value which is 0. Button + will increment the current value by 1 and Button – with decrement value by 1.

This state is managed by React.useState Hook.

Step 2: Make Changes in index.Js File

Make changes in index.Js file according to the given code below.

index.js



In the above code, we have imported ButtonCounter and in the ReactDOM.render we are calling it.

Step 3: Start the React Application

Save all the changes first. Come to the terminal window and type npm start command. Hit Enter. You will get below results. Test application by clicking on + and buttons, and see whether it is working as expected or not. To get initial value (which is 0) just click on Reset button.

How to Create Your First React Hook



You have successfully created your first React Hook. In the upcoming article, we will see One-way Data Flow in React.

Tutorial Funda

Tutorial Funda will keep you updated with the latest Programming Languages, Software Tools and related technologies used in Software Development.

Leave a Reply

Your email address will not be published. Required fields are marked *