DEV Community

Manipriyan
Manipriyan

Posted on

Managing State in React Functional Components with useState Hook

Hello everyone!

As a developer, I'm always looking for ways to make my code more efficient and organized. That's why I want to talk about one of my favorite tools in React - the useState hook!

useState is a hook that allows you to add state to your functional components. It's a great alternative to using class components and this.setState.

Let's dive deeper into the useState hook in React and explore how it works with some detailed examples.

What is useState?
useState is a hook in React that allows us to add state to our functional components. It's a replacement for using this.state and this.setState in class components. With the useState hook, we can manage state in a functional component just like we would in a class component.

Syntax of useState
The syntax of useState is quite simple. It's a function that takes an initial value and returns an array with two elements. The first element is the current state value, and the second element is a function that we can use to update the state.

const [state, setState] = useState(initialValue);

Enter fullscreen mode Exit fullscreen mode

Let's take a look at some examples to see how we can use the useState hook in our code.

Example 1 - Counter
Let's start with a simple counter example. In this example, we'll create a button that increases a count by one each time it's clicked.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  function handleIncrement() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

export default Counter;

Enter fullscreen mode Exit fullscreen mode

In this code, we import the useState hook from React and use it to create a state called count. We initialize the count to 0, and also create a function called handleIncrement that will update the count value when the button is clicked.

We then render the current count value and the button that will trigger the handleIncrement function. When the button is clicked, it will call the setCount function and update the count value accordingly.

Example 2 - Form
Let's move on to a more complex example. In this example, we'll create a form with input fields for a name and email. We'll use the useState hook to manage the state of the input fields.

import React, { useState } from 'react';

function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  function handleNameChange(e) {
    setName(e.target.value);
  }

  function handleEmailChange(e) {
    setEmail(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
    console.log(`Name: ${name}, Email: ${email}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" value={name} onChange={handleNameChange} />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input type="email" id="email" value={email} onChange={handleEmailChange} />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default Form;

Enter fullscreen mode Exit fullscreen mode

In this code, we create two states - name and email - and initialize them to empty strings. We also create two functions - handleNameChange and handleEmailChange - that will update the state values when the input fields are changed.

We also create a function called handleSubmit that will log the current name and email values to the console when the form is submitted. Finally, we render the form with the input fields and the submit button.

Example 3 - Toggle
Let's take a look at one more example - a simple toggle. In this example, we'll use the useState hook to toggle the visibility of a piece of text.

import React, { useState } from 'react';

function Toggle() {
  const [isVisible, setIsVisible] = useState(false);

  function handleToggle() {
    setIsVisible(!isVisible);
  }

  return (
    <div>
      <button onClick={handleToggle}>{isVisible ? 'Hide' : 'Show'}</button>
      {isVisible && <p>This text is visible when the button is clicked.</p>}
    </div>
  );
}

export default Toggle;

Enter fullscreen mode Exit fullscreen mode

In this code, we create a state called isVisible and initialize it to false. We also create a function called handleToggle that will toggle the state value when the button is clicked.

We then render the button with the text 'Show' or 'Hide', depending on the current state value. We also render the text when isVisible is true.

Conclusion
In conclusion, the useState hook is a powerful tool that allows us to manage state in functional components in React. With useState, we can easily add state to our components and update it as needed. Hopefully, these examples have helped you understand how to use useState in your own React projects.

Top comments (0)