The blessed ‘useState’ Hook

Manan Sharma
5 min readMar 11, 2020

I started working with ReactJS (referred further as React) in 2019, at the very beginning of my Undergrad in Computer Engineering, and since then, I have become a big fan of everything that it brings to the table.

Introduction

Before we begin, I want to just re-iterate what React is and what it does.

As defined by the official docs, React is a component-driven front-end JavaScript library for building user interfaces.

This perfectly sums up everything that React can do and is being used for. But a little depth on the highlights will be very helpful for our understanding

  1. component-driven : For handling complex UI’s, React workflow will break everything down to components which can then be used independently on multiple screens/pages. A component could be as simple as a Button or a full-fledged Text-Area but at it’s core, it has the capability of being independently managed by React.
  2. library: React is a JavaScript Library, please don’t confuse it as a runtime or a programming language on it’s own. It provides a simple API which can be used via JavaScript to access all the functionality React has to offer.
  3. user interfaces: React started as a front-end framework only and primarily remains the same. But the community has worked out to create a full fledged Router for handling client-side routing and complex state managers like Redux, which allows you to create full-stack React based web-apps easily.

Functional-Components

Now let’s dive into the topic. React introduced Functional/Stateless Components in React v14, which were hailed as revolutionary back at that time.

It had some significant advantages over the primary Class-Based Components which were:

  1. They were cleaner and a whole lot less verbose.
  2. They steered away from the sometimes frustrating this binding.
  3. They had a clear cut syntax for rendering a component by just using return

All these advantages were great, but one thing bogged down the perfect adaptability of Functional Components, which was, they were not able to use State. :(

State, in a nutshell, is an object or a value tracked by a component in React. A re-render of that component happens if the State changes. State is defined for every component individually.

Sounds useful right? It is. Class-Based components easily allowed the use of State with the state object defined in their constructor . But the newly introduced Functional Components could not use it.

This was by plan as well, Functional Components were introduced for providing a simpler syntax to simple components for which complexities like ‘State’ and ‘this-binding’ etc. were overkill.

But the community, wanted to extend their use further. They wanted the developers to use the simpler syntax offered by Functional Components along with the full-fledged React features offered in Class-Based Components, and so, in React v16.8 hooks were introduced which changed the game by implementing exactly this.

Hooks

So what are Hooks?

Hooks are functions that let you “hook into” React state and lifecycle features from functional components.

Sounds simple ? Basically they are functions which can be used inside Functional Components (only). And then provide the functionality which could only be used by Class-Based components before.

Some important points about Hooks

  1. They are provided as named exports on the react module/package.
  2. They can only be used in Functional Components and not in Class-Based Components.
  3. They begin with the prefix ‘use’ eg. useState , useReducer etc.
import React, {useState, useContext} from 'react'

This led to a major change in the naming convention as well. Functional Components were previously called as Stateless Components. But as the useState hook allowed the use of ‘State’ in them. They are no longer referred with that name. (since React v16+)

The useState Hook

Hopefully, you now have a bit refreshed knowledge about React, Components and Hooks. So let’s dive in to understand the most important Hook, the useState hook.

Usage :

//import signature
import React, {useState} from 'react';
/*1. Called with a single value which will be used the initialize the state variable.
2. Returns
a> a variable which will be tracked as state
b> a function used to change value of that variable and
re-render the component(if changed)
as an array which should be de-structured as a good practice.

eg:
*/const CounterApp = (props) => {
const [count, setCount] = useState(1);
return(
<div>
Current Count is : {count}
</div>
)
}

The above example indicates a simple use case for the useState hook to create a counter-app where the current count is managed by the ‘state’.

In depth:

  1. count : [State-Variable] This variable will be used to track state now. It will be initailsed with the integer 1 upon component mount. All further changes made to state can be accessed using this variable. It can be named anything and doesn’t have a particular naming syntax.
  2. setCount : [State-Updater] This is similar to the setState() API. And is used to set new values to the state directly. It doesn’t need to have a similar name as the state variable but it is recommended along with the prefix ‘set’

A simple counter app will look like (code-snippet) :

Code snippet of the counter app using hooks

Best Practices for useState

  1. Always create multiple useState calls for multiple values to be tracked as state i.e. use the hook for every individual value instead of creating a single object with those values and tracking it as a whole. which means
// Avoid:const [stateObject, setStateObject] = useState({ key1: value1, key2: value2})// Instead
const [key1, setKey1] = useState(value1);
const [key2, setKey2] = useState(value2);

This is because the state-updater force replaces the previous state with the new value being passed, unlike setState() . That is, the whole stateObject is rewritten if you pass a new value in setStateObject .

// Initial
stateObject: {
key1: value1,
key2: value2
}
// Use of state-updates
setStateObject({ key1: newValue1 })
// New updated state
stateObject: {
key1: newValue1
}

If we want to avoid this we would have to pass the value of every state object property individually while changing any one of the values which is very tedious. Therefore, it is recommended to use individual useState class.

2. Always follow the standardized naming conventions (mentioned above) while creating state variables or using any Hook for that matter

With this, I hope I was able to add to your knowledge by covering every use-case scenario of the useState hook. I’ll be writing more about other Hooks in future posts. Stay tuned!

Happy Coding!

--

--

Manan Sharma

A Computer Sc. undergrad at Delhi Technological University. Trying to make an impact in this world, one keystroke at a time.