Learn how to useState Hook in React

Learn how to useState Hook in React

React Hooks – What is it trying to solve? Hooks were introduced in React version 16.8. How to use State hook? The purpose of the useState hook is to add state to your functional components in React, without having to use a class. ‘Hooks are functions that let you “hook into” React state and lifecycle features from function component

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

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

Learn React.js: Front-End Web Development for Beginners

Learn React.js: Front-End Web Development for Beginners

Learn React.js - Frontend Web Development for Beginners. In this React tutorial, you will learn the core fundamentals of React JS and Modern JavaScript so that you can start building lightning fast web apps using React JS. Learn Modern JavaScript and React JS from absolute scratch. Learn to make AJAX requests to get data from remote API and display into your web application. Learn React JS, which is one of the most exciting technology of recent time

Learn React.js - Frontend Web Development for Beginners - Web Development in 2019. In this video you will learn the core fundamentals of React JS and Modern JavaScript so that you can start building lightning fast web apps using React JS.

In this video, you will learn Modern JavaScript and React JS from absolute scratch. you will learn to make AJAX requests to get data from remote API and display into your web application.

So if you are ready to learn React JS, which is one of the most exciting technology of recent time

Thanks for watching

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

React - The Complete Guide (incl Hooks, React Router, Redux)

**☞ **Modern React with Redux [2019 Update]

**☞ **50+ Java Interview Questions for Programmers

**☞ **Top 100 Python Interview Questions and Answers

**☞ **100+ Basic Machine Learning Interview Questions and Answers

**☞ **Introduction to Java String Interview Questions and Answers

**☞ **Best 50 React Interview Questions and Answers in 2019

**☞ **Top 50+ SQL Interview Questions and Answers in 2019

**☞ **Best Java Microservices Interview Questions In 2019

**☞ **Best 50 Nodejs interview questions from Beginners to Advanced in 2019

**☞ **100+ Java Interview Questions and Answers In 2019

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.