State: A Component's Memory·续4

if (isSent) { return <h1>Thank you!</h1>; } else { return ( <form onSubmit={e => { e.preventDefault(); alert(Sending: "${message}"); setIsSent(true); }}> <textarea placeholder="Message" value={message} onChange={e => setMessage(e.target.value)} /> <br /> <button type="submit">Send</button> </form> ); } }


Remember, Hooks must be called unconditionally and always in the same order!

You could also remove the unnecessary `else` branch to reduce the nesting. However, it's still important that all calls to Hooks happen *before* the first `return`.

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

export default function FeedbackForm() {
  const [isSent, setIsSent] = useState(false);
  const [message, setMessage] = useState('');

if (isSent) {
    return &lt;h1>Thank you!&lt;/h1>;
  }

return (
    &lt;form onSubmit={e => {
      e.preventDefault();
      alert(`Sending: "${message}"`);
      setIsSent(true);
    }}>
      &lt;textarea
        placeholder="Message"
        value={message}
        onChange={e => setMessage(e.target.value)}
      />
      &lt;br />
      &lt;button type="submit">Send&lt;/button>
    &lt;/form>
  );
}

Try moving the second useState call after the if condition and notice how this breaks it again.

If your linter is configured for React, you should see a lint error when you make a mistake like this. If you don't see an error when you try the faulty code locally, you need to set up linting for your project.

Remove unnecessary state

When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason the first time it shows "Hello, !", and then "Hello, [name]!" with the previous input every time after.

To fix this code, remove the unnecessary state variable. (We will discuss about why this didn't work later.)

Can you explain why this state variable was unnecessary?

import { useState } from 'react';

export default function FeedbackForm() {
  const [name, setName] = useState('');

function handleClick() {
    setName(prompt('What is your name?'));
    alert(`Hello, ${name}!`);
  }

return (
    &lt;button onClick={handleClick}>
      Greet
    &lt;/button>
  );
}

Here is a fixed version that uses a regular name variable declared in the function that needs it:

export default function FeedbackForm() {
  function handleClick() {
    const name = prompt('What is your name?');
    alert(`Hello, ${name}!`);
  }

return (
    &lt;button onClick={handleClick}>
      Greet
    &lt;/button>
  );
}

A state variable is only necessary to keep information between re-renders of a component. Within a single event handler, a regular variable will do fine. Don't introduce state variables when a regular variable works well.


Sitemap

Overview of all docs pages