Learn the useState React Hook

Adhithi Ravichandran
4 min readJan 15, 2020

--

If you are a React developer, and haven’t learned about React hooks yet, it is the perfect time to start learning now. In this post, we are specifically going to learn about the very first React Hook, the useState.

Before we get started, here is a little background about what this is all about.

React Hooks — What is it trying to solve?

Hooks were introduced in React version 16.8 and now used by many teams that use React.

Hooks solves the problem of code reuse across components. They are written without classes. This does not mean that React is getting rid of classes, but hooks is just an alternate approach.

In React, you can soon end up with complex components with stateful logic. It is not easy to break these components because within the class you are dependent on the React Lifecycle Methods. That’s where React Hooks come in handy. They provide you a way to split a component, into smaller functions. Instead of splitting code based on the Lifecycle methods, you can now organize and split your code into smaller units based on functionality.

This is a huge win for React developers. We have always been trained to write React classes which adhere to the confusing lifecycle methods. Things are going to get better with the introduction of hooks to React.

‘Hooks are functions that let you “hook into” React state and lifecycle features from function component. They do not work within a class. They let you use React without a class.’ — React Official Blog post.

How to use State hook?

Alright, so now we know why hooks were introduced, now let’s dive deep into the useState hook in this blog post. The purpose of the useState hook is to add state to your functional components in React, without having to use a class.

Traditional Class Component

Let’s look into an example to see how we can convert a class component into a functional component and manage state using the useState hook.

I am creating a YesNoComponent, that contains two buttons (Yes and No). When Yes is pressed, it sets the buttonPressed state to “Yes”, and when No is pressed, it sets the buttonPressed state to “No”.

import React from "react";class YesNoComponent extends React.Component {
state = {
buttonPressed: ""
};
onYesPress() {
this.setState({ buttonPressed: "Yes" });
console.log("Yes was pressed");
}
onNoPress() {
this.setState({ buttonPressed: "No" });
console.log("No was pressed");
}
render() {
return (
<div>
<button onClick={() => this.onYesPress()}>Yes</button>
<button onClick={() => this.onNoPress()}>No</button>
</div>
);
}
}
export default YesNoComponent;

Functional Component with Hooks

Now let’s rewrite this component into a functional component. We are going to get rid of the class and instead just use a functional component. You may ask, then how do we manage the local state? Well, that’s where we are going to use React’s useState hook.

Let’s take a look at the rewritten component below:

import React, { useState } from "react";const YesNoComponentFunctional = () => {
const [button, setButton] = useState("");
const onYesPress = () => {
setButton("Yes");
console.log({ button });
};
const onNoPress = () => {
setButton("No");
console.log({ button });
};
return (
<div>
<button onClick={() => onYesPress()}>Yes</button>
<button onClick={() => onNoPress()}>No</button>
</div>
);
};
export default YesNoComponentFunctional;

The above component generates the same result as the previous YesNoComponent. The only difference is that this is a functional component while the other was written in a class.

useState Details

There are few important pieces in this code that made this happen. Let’s look at each one of them.

The first thing we need to do is import the useState from React.

import React, { useState } from "react";

The next step is to declare the state variable for the component

const [button, setButton] = useState("");

Here we have a declared a new state variable called button. The useState then sets the initial value for button here as and empty string “”. useState is the same as this.state in our class components.

What does useState return?

It returns a pair of values: the current state and a function that updates it. In our example, the current state is button and the function that updates it is setButton. Here setButton is going to behave the same as setState from the previous example.

Notice in the onYesPress() and onNoPress() functions the setButton function is used to set the current state of the button.

What Does useState Hook Achieve?

Alright, we saw how we can convert a class component into a functional component in React and use state within the functional component using the useState hook. But what does this really achieve, or why was this feature added?

  • Readability and Simplicity: The main reasons behind introducing Hooks, is the readability and simplicity aspects of code. With simple and pure functional components, now the code is a lot easier to read and understand. With classes, the code could get complex for some components.
  • Classes can be confusing: Developers who learn React, can find it difficult, when they have to learn one more new concept like classes. Classes can be harder to learn and understand for newer developers. They need to learn how this works, how binding works and so on. When components are written with functions instead, newer developers may have a much less learning curve.

Conclusion

This post was originally posted in https://programmingwithmosh.com/

Hooks is a fairly newer concept in React, and the official React documentation does not recommend that you rewrite all your components using Hooks. Instead, you can start writing your newer components using Hooks.

If you want to play with the code samples I used in this blog post, they are available on my GitHub Repo below:

React Hooks Examples

Resources:

React Hooks Doc

Functional Components vs. Class Components

There are other hooks in addition to the useState hook, that we will cover in another blog post. I hope you enjoyed this post. Please share it and you can follow me on twitter at @AdhithiRavi

--

--

Adhithi Ravichandran
Adhithi Ravichandran

Written by Adhithi Ravichandran

Software Consultant, Author, Speaker, React|Next.js|React Native |GraphQL|Cypress|Playwright Dev & Indian Classical Musician

No responses yet