Search code examples
reactjscomponentsstate

Preserving state for removed components in React


This is a challenge from the React Docs Beta site. The solution I used was not one that they offered at the end of the challenge. I am wondering if this is bad practice. To preserve state between removed components I used the same key on the <Form/> component. This seems to work.

import { useState } from 'react';

export default function App() {
  const [showHint, setShowHint] = useState(false);
  if (showHint) {
    return (
      <div>
        <p><i>Hint: Your favorite city?</i></p>
        <Form key="form1" />
        <button onClick={() => {
          setShowHint(false);
        }}>Hide hint</button>
      </div>
    );
  }
  return (
    <div>
      <Form key="form1" />
      <button onClick={() => {
        setShowHint(true);
      }}>Show hint</button>
    </div>
  );
}

function Form() {
  const [text, setText] = useState('');
  return (
    <textarea
      value={text}
      onChange={e => setText(e.target.value)}
    />
  );
}

Solution

  • I highly doubt that it's good practice. Instead I would recommend to keep the changing tags in one single return statement and render them conditionally.

    Your app component would then look like this:

    export default function App() {
      const [showHint, setShowHint] = useState(false);
      return (
        <div>
          {showHint && (
            <p>
              <i>Hint: Your favorite city?</i>
            </p>
          )}
          <Form />
          <button onClick={() => setShowHint(!showHint)}>
            {`${showHint ? "Hide" : "Show"} hint`}
          </button>
        </div>
      );
    }
    

    The above example would also minimize code duplication.