Understanding React Hooks

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.

Importing:

import React,{useState} from 'react';

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.

function App()
{ const [count,setCount] = React.useState(0);
function increase()
{ setCount(count+1); }
function decrease()
{ setCount(count-1); }
return (<div>
<h1>{count}</h1>
<button onClick={increase}>+</button>
<button onClick={decrease}>-</button>
</div>)
}

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: https://github.com/Akankshap38/React-Projects/tree/master/first-react-app

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:

Dynamically heading of the page is appended with user input

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.

const [fullName, setFullName] = useState({
fname : "",
lname : ""
});

The function called onChange event:

function updateHeading(event){
console.log(event.target.name);
setFullName(prevValue =>{ //prevValue stores last input field values
if(event.target.name==="fName")
{
return {
fname:event.target.value,
lname:prevValue.lname //using previous lname if lname field was //unchanged
}
}
else if(event.target.name==="lName")
{
return {
fname:prevValue.fname,
lname:event.target.value
}
}
console.log(fullName);
});
}

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.

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

Recommended from Medium

React Native as a Service

It’s time to say HI to Angular and Goodbye to the other Front-end Frameworks

React Native Conf @ 2019 — Two Cents 💯

How I’m teaching the kids coding for the web

WLST script to change the log settings for all the servers in the weblogic domain

React local development and testing mocking with msw and mswjs/data

The Power of GraphQL, With RESTful APIs: Meet Hypnos

IIFE: A mini-lesson in Javascript history

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
Akanksha Pardeshi

Akanksha Pardeshi

Learner. Observer. Interested in software development.

More from Medium

React JS Bad Practices

Redux Persist In React Application

React State Management: Hook