📜  react useState - Javascript(1)

📅  最后修改于: 2023-12-03 15:19:44.822000             🧑  作者: Mango

React useState

In React, useState is a hook that allows you to add state to your functional components. It replaces the need for class components to have a constructor and declare a state object. useState can be used multiple times in a single component, allowing you to have multiple independent pieces of state in a single functional component.

Usage

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

import React, { useState } from 'react';

Then, within your functional component, you can declare a piece of state using the useState hook:

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

This code declares a piece of state called count and sets its initial value to 0. The useState hook returns an array with two values: the current state value (count in this case) and a function to update the state (setCount in this case).

You can then use count and setCount within your component just like you would with any other state object and its corresponding setState function:

return (
  <div>
    <p>Current count: {count}</p>
    <button onClick={() => setCount(count + 1)}>Increment</button>
  </div>
);

The code above displays the current value of count and provides a button to increment the count when clicked. The setCount function updates the value of count.

Multiple pieces of state

As mentioned earlier, you can use useState multiple times in a single component to have multiple independent pieces of state. For example:

const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');

return (
  <form>
    <label>
      First name:
      <input
        type="text"
        value={firstName}
        onChange={e => setFirstName(e.target.value)}
      />
    </label>
    <label>
      Last name:
      <input
        type="text"
        value={lastName}
        onChange={e => setLastName(e.target.value)}
      />
    </label>
  </form>
);

The code above declares two pieces of state (firstName and lastName) and provides inputs for the user to update the values. Each piece of state has its own corresponding setState function (setFirstName and setLastName).

Conclusion

useState is a powerful hook that simplifies the process of adding state to functional components in React. It allows you to declare multiple independent pieces of state and provides an easy-to-use API for updating those states. With the help of useState, you can create more dynamic and interactive components in your React applications.