Unlocking the Power of React Hooks: The useState

Unlocking the Power of React Hooks: The useState

Learn how to add state and other functionality to your functional components in React with the powerful useState hook.

ยท

4 min read

Introduction

In the previous blog we discussed what React Hooks are and how to use them effectively.

Hooks allow developers to add state and other functionality to functional components. One of the most commonly used hooks is useState. In this blog, we will explore what useState is, why it is useful, how to use it and in the end, we will be creating a basic Form to get familiar with this hook.

What is useState?

useState is a hook that allows you to add state to a functional component.

In React, state is an object that holds the data that determines how a component should be rendered.

When the state of a component changes, React automatically re-renders the component, updating the UI to reflect the new state.

How to use useState?

Now we have gained some knowledge about useState. So let's jump to the fun part i.e code.

useState returns an array with exactly two items:

  1. The current state of this state variable, initially set to the initial state you provided.

  2. The set function that lets you change it to any other value in response to interaction.

To use useState, we first need to import it from the React library:

import React, { useState } from "react";

Then, we can declare state in a functional component like this:

function MyComponent() {
  const [age, setAge] = useState(10);
  //...

In the above example, we declare a state variable called age with an initial value of 10. We also declare a function called setAge that we can use to update the value of age.

We can then use age and setAge in our component to manage state.

For example, we could use them to display the current age and update it when a button is clicked:

In the above example, we define a function called handleButtonClick that updates the age state variable by calling setAge. We then use this function as the onClick handler for a button that increments the count.

Here's the link to the demo


Let's create a Form

This is an advanced section where we will be learning about how we can use useState with objects to create a form.

Before jumping into this section you can experiment with the above example we used so that you get to understand this section in a better way.

import React, { useState } from "react";

function SportsForm() {
  // ๐Ÿ“ Declare state using useState
  const [formData, setFormData] = useState({
    name: "",
    age: "",
    favoriteSport: "",
  });
}

In the above snippet, we are declaring the variables we will be using to take inputs from the user. We are using three variables name , age and favoriteSport.

Now we will be creating the function which would handle how the states of these variables change when the user changes their value.

 // ๐Ÿ”ง Define a function to update the form data state
  function handleInputChange(event) {
    const { name, value } = event.target;
    // ๐Ÿค Update the formData state using setFormData
    setFormData({ ...formData, [name]: value });
  }

handleInputChange handles the change of state. One question that might have come to your mind would be "earlier we used a very simple way to update value, but here we are using (...)".

If I was reading this article while starting my journey of learning hooks, then this question would surely have struck my mind.

If an object is contained within a Hook, it cannot be updated directly. If you call the functional updater and pass arguments directly, the values within the Hook will be replaced instead of merged. To ensure merging, we are using a spread operator (โ€ฆ).

Now, we will be creating a function that captures the response when the user clicks on "๐Ÿš€ Submit".

 // ๐Ÿ“ค Define a function to handle form submission
  function handleSubmit(event) {
    event.preventDefault();
    console.log(formData);
    // ๐Ÿš€ Perform form submission logic (e.g., send data to API or send via email)
  }

Here's the complete code:

Conclusion

useState is a powerful hook that allows us to add state to functional components in React.

By using useState, we can write simpler and more maintainable code, and create components that are interactive and responsive to user input.

I hope this introduction to useState has been helpful, and you feel more confident using this hook in your own React projects!

Will meet you in the next one. Till then keep on practicing.

Did you find this article valuable?

Support Utkarsh Nagar by becoming a sponsor. Any amount is appreciated!

ย