Photo by Grace To on Unsplash

Hooks are some new utility in React which helps reducing redundant code and saves time.

Defination of Hook as per the official doc:

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. (We don’t recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you’d like.)

One use case of hook: render() is called only once that is at the time of loading the page. But there maybe the need to change somethings(like UI) of only one section of page without touching other section or without reloading. For example, hitting like button or adding comments.

Important hook is useState hook. We will have a look at how useState is used.


Usage of useState: In this example, a simple counter is created. On clicking + button, counter value increases and counter value decreases if - button is clicked.

useState has only one argument that is initial state of the entity which is going to change over time using events like on button click, etc. useState return two values, first is the entity that is going to change and other is the callback function that let us change the value of the entity.

Sample React application which is a simple timer which update timer component every second:

How to use useState for complex state changes?

Suppose, we need to display inputs user is currently filling. Something like this:

Initial state:

After user start entering in the input fields:

We use onChange attribute of form input tag to call a function which is responsible to change the heading dynamically on every change made in input fields. Suppose hook is used for maintaining first and last name of a person.

The function called onChange event:

prevValue contains values of input which was there just before the latest change made by the user.

The whole working code can be found here.

Learner. Observer. Interested in software development.