添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

useState is a React Hook that lets you add a state variable to your component.

const [state, setState] = useState(initialState)

Reference

useState(initialState)

Call useState at the top level of your component to declare a state variable.

import { useState } from 'react';

function MyComponent() {
const [age, setAge] = useState(28);
const [name, setName] = useState('Taylor');
const [todos, setTodos] = useState(() => createTodos());
// ...

The convention is to name state variables like [something, setSomething] using array destructuring.

See more examples below.

Parameters

  • initialState : The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
  • If you pass a function as initialState , it will be treated as an initializer function . It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. See an example below.
  • Returns

    useState returns an array with exactly two values:

  • The current state. During the first render, it will match the initialState you have passed.
  • The set function that lets you update the state to a different value and trigger a re-render.
  • Caveats

  • useState is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
  • In Strict Mode, React will call your initializer function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.
  • set functions, like setSomething(nextState)

    The set function returned by useState lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state:

    const [name, setName] = useState('Edward');

    function handleClick() {
    setName('Taylor');
    setAge(a => a + 1);
    // ...

    Parameters

  • nextState : The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions.
  • If you pass a function as nextState , it will be treated as an updater function . It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. See an example below.
  • Returns

    set functions do not have a return value.

    Caveats

    The set function only updates the state variable for the next render . If you read the state variable after calling the set function, you will still get the old value that was on the screen before your call.

    If the new value you provide is identical to the current state , as determined by an Object.is comparison, React will skip re-rendering the component and its children. This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn’t affect your code.

    React batches state updates. It updates the screen after all the event handlers have run and have called their set functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use flushSync .

    Calling the set function during rendering is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to store information from the previous renders . See an example below.

    In Strict Mode, React will call your updater function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.

    Usage

    Adding state to a component

    Call useState at the top level of your component to declare one or more state variables.

    import { useState } from 'react';

    function MyComponent() {
    const [age, setAge] = useState(42);
    const [name, setName] = useState('Taylor');
    // ...

    The convention is to name state variables like [something, setSomething] using array destructuring.

    useState returns an array with exactly two items:

  • The current state of this state variable, initially set to the initial state you provided.
  • The set function that lets you change it to any other value in response to interaction.
  • To update what’s on the screen, call the set function with some next state:

    function handleClick() {
    setName('Robin');
    }

    React will store the next state, render your component again with the new values, and update the UI.

    Pitfall

    Calling the set function does not change the current state in the already executing code :

    function handleClick() {
    setName('Robin');
    console.log(name); // Still "Taylor"!
    }

    It only affects what useState will return starting from the next render.

    Basic useState examples

    Example 1 of 4 :
    Counter (number)

    In this example, the count state variable holds a number. Clicking the button increments it.

    import { useState } from 'react';
    export default function Counter() {
      const [count, setCount] = useState(0);
      function handleClick() {
        setCount(count + 1);
      return (
        <button onClick={handleClick}>
          You pressed me {count} times
        </button>