useState·续1

Passing the updater function

This example passes the updater function, so the "+3" button works.

import { useState } from 'react';

export default function Counter() {
  const [age, setAge] = useState(42);

function increment() {
    setAge(a => a + 1);
  }

return (
    <>
      <h1>Your age: {age}</h1>
      <button onClick={() => {
        increment();
        increment();
        increment();
      }}>+3</button>
      <button onClick={() => {
        increment();
      }}>+1</button>
    </>
  );
}
button { display: block; margin: 10px; font-size: 20px; }
h1 { display: block; margin: 10px; }

Passing the next state directly

This example does not pass the updater function, so the "+3" button doesn't work as intended.

import { useState } from 'react';

export default function Counter() {
  const [age, setAge] = useState(42);

function increment() {
    setAge(age + 1);
  }

return (
    <>
      <h1>Your age: {age}</h1>
      <button onClick={() => {
        increment();
        increment();
        increment();
      }}>+3</button>
      <button onClick={() => {
        increment();
      }}>+1</button>
    </>
  );
}
button { display: block; margin: 10px; font-size: 20px; }
h1 { display: block; margin: 10px; }

Updating objects and arrays in state

You can put objects and arrays into state. In React, state is considered read-only, so you should replace it rather than mutate your existing objects. For example, if you have a form object in state, don't mutate it:

// 🚩 Don't mutate an object in state like this:
form.firstName = 'Taylor';

Instead, replace the whole object by creating a new one:

// ✅ Replace state with a new object
setForm({
  ...form,
  firstName: 'Taylor'
});

Read updating objects in state and updating arrays in state to learn more.

Form (object)

In this example, the form state variable holds an object. Each input has a change handler that calls setForm with the next state of the entire form. The { ...form } spread syntax ensures that the state object is replaced rather than mutated.

import { useState } from 'react';

export default function Form() {
  const [form, setForm] = useState({
    firstName: 'Barbara',
    lastName: 'Hepworth',
    email: 'bhepworth@sculpture.com',
  });

return (
    <>
      <label>
        First name:
        <input
          value={form.firstName}
          onChange={e => {
            setForm({
              ...form,
              firstName: e.target.value
            });
          }}
        />
      </label>
      <label>
        Last name:
        <input
          value={form.lastName}
          onChange={e => {
            setForm({
              ...form,
              lastName: e.target.value
            });
          }}
        />
      </label>
      <label>
        Email:
        <input
          value={form.email}
          onChange={e => {
            setForm({
              ...form,
              email: e.target.value
            });
          }}
        />
      </label>
      <p>
        {form.firstName}{' '}
        {form.lastName}{' '}
        ({form.email})
      </p>
    </>
  );
}
label { display: block; }
input { margin-left: 5px; }

Form (nested object)

In this example, the state is more nested. When you update nested state, you need to create a copy of the object you're updating, as well as any objects "containing" it on the way upwards. Read updating a nested object to learn more.

import { useState } from 'react';

export default function Form() {
  const [person, setPerson] = useState({
    name: 'Niki de Saint Phalle',
    artwork: {
      title: 'Blue Nana',
      city: 'Hamburg',
      image: 'https://react.dev/images/docs/scientists/Sd1AgUOm.jpg',
    }
  });

function handleNameChange(e) {
    setPerson({
      ...person,
      name: e.target.value
    });
  }

function handleTitleChange(e) {
    setPerson({
      ...person,
      artwork: {
        ...person.artwork,
        title: e.target.value
      }
    });
  }

function handleCityChange(e) {
    setPerson({
      ...person,
      artwork: {
        ...person.artwork,
        city: e.target.value
      }
    });
  }

function handleImageChange(e) {
    setPerson({
      ...person,
      artwork: {
        ...person.artwork,
        image: e.target.value
      }
    });
  }

return (
    <>
      <label>
        Name:
        <input
          value={person.name}
          onChange={handleNameChange}
        />
      </label>
      <label>
        Title:
        <input
          value={person.artwork.title}
          onChange={handleTitleChange}
        />
      </label>
      <label>
        City:
        <input
          value={person.artwork.city}
          onChange={handleCityChange}
        />
      </label>
      <label>
        Image:
        <input
          value={person.artwork.image}
          onChange={handleImageChange}
        />
      </label>
      <p>
        <i>{person.artwork.title}</i>
        {' by '}
        {person.name}
        <br />
        (located in {person.artwork.city})
      </p>
      <img
        src={person.artwork.image}
        alt={person.artwork.title}
      />
    </>
  );
}
label { display: block; }
input { margin-left: 5px; margin-bottom: 5px; }
img { width: 200px; height: 200px; }

List (array)

In this example, the todos state variable holds an array. Each button handler calls setTodos with the next version of that array. The [...todos] spread syntax, todos.map() and todos.filter() ensure the state array is replaced rather than mutated.

```js src/App.js import { useState } from 'react'; import AddTodo from './AddTodo.js'; import TaskList from './TaskList.js';

let nextId = 3; const initialTodos = [ { id: 0, title: 'Buy milk', done: true }, { id: 1, title: 'Eat tacos', done: false }, { id: 2, title: 'Brew tea', done: false }, ];

export default function TaskApp() { const [todos, setTodos] = useState(initialTodos);

function handleAddTodo(title) { setTodos([ ...todos, { id: nextId++, title: title, done: false } ]); }

function handleChangeTodo(nextTodo) { setTodos(todos.map(t => { if (t.id === nextTodo.id) { return nextTodo; } else { return t; } })); }

function handleDeleteTodo(todoId) { setTodos( todos.filter(t => t.id !== todoId) ); }

return ( <> </> ); }


```js src/AddTodo.js
import { useState } from 'react';

export default function AddTodo({ onAddTodo }) {
  const [title, setTitle] = useState('');
  return (
    <>
      <input
        placeholder="Add todo"
        value={title}
        onChange={e => setTitle(e.target.value)}
      />
      <button onClick={() => {
        setTitle('');
        onAddTodo(title);
      }}>Add</button>
    </>
  )
}

```js src/TaskList.js import { useState } from 'react';

export default function TaskList({ todos, onChangeTodo, onDeleteTodo }) { return (

    {todos.map(todo => (
  • ))}
); }

function Task({ todo, onChange, onDelete }) { const [isEditing, setIsEditing] = useState(false); let todoContent; if (isEditing) { todoContent = ( <> { onChange({ ...todo, title: e.target.value }); }} /> </> ); } else { todoContent = ( <> {todo.title} </> ); } return ( ); }


```css
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }

Writing concise update logic with Immer

If updating arrays and objects without mutation feels tedious, you can use a library like Immer to reduce repetitive code. Immer lets you write concise code as if you were mutating objects, but under the hood it performs immutable updates:

import { useState } from 'react';
import { useImmer } from 'use-immer';

let nextId = 3;
const initialList = [
  { id: 0, title: 'Big Bellies', seen: false },
  { id: 1, title: 'Lunar Landscape', seen: false },
  { id: 2, title: 'Terracotta Army', seen: true },
];

export default function BucketList() {
  const [list, updateList] = useImmer(initialList);

function handleToggle(artworkId, nextSeen) {
    updateList(draft => {
      const artwork = draft.find(a =>
        a.id === artworkId
      );
      artwork.seen = nextSeen;
    });
  }

return (
    <>
      <h1>Art Bucket List</h1>
      <h2>My list of art to see:</h2>
      <ItemList
        artworks={list}
        onToggle={handleToggle} />
    </>
  );
}

function ItemList({ artworks, onToggle }) {
  return (
    <ul>
      {artworks.map(artwork => (
        <li key={artwork.id}>
          <label>
            <input
              type="checkbox"
              checked={artwork.seen}
              onChange={e => {
                onToggle(
                  artwork.id,
                  e.target.checked
                );
              }}
            />
            {artwork.title}
          </label>
        </li>
      ))}
    </ul>
  );
}

```json package.json { "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }


---

### Avoiding recreating the initial state

React saves the initial state once and ignores it on the next renders.

```js
function TodoList() {
  const [todos, setTodos] = useState(createInitialTodos());
  // ...

Although the result of createInitialTodos() is only used for the initial render, you're still calling this function on every render. This can be wasteful if it's creating large arrays or performing expensive calculations.

To solve this, you may pass it as an initializer function to useState instead:

function TodoList() {
  const [todos, setTodos] = useState(createInitialTodos);
  // ...

Notice that you’re passing createInitialTodos, which is the function itself, and not createInitialTodos(), which is the result of calling it. If you pass a function to useState, React will only call it during initialization.

React may call your initializers twice in development to verify that they are pure.

Passing the initializer function

This example passes the initializer function, so the createInitialTodos function only runs during initialization. It does not run when component re-renders, such as when you type into the input.

```js import { useState } from 'react';

function createInitialTodos() { const initialTodos = []; for (let i = 0; i < 50; i++) { initialTodos.push({ id: i, text: 'Item ' + (i + 1) }); } return initialTodos; }

export default function TodoList() { const [todos, setTodos] = useState(createInitialTodos); const [text, setText] = useState('');