Learn how to useState Hook in React

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

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

Originally published by https://programmingwithmosh.com

#react-js #javascript #web-development

Learn how to useState Hook in React
6.80 GEEK