Dwarves
Memo
Type ESC to close search bar

Preserving and Resetting state in React

Why should you read this article?

const [isPlayerA, setIsPlayerA] = useState(true)

function Counter(name) {
  const [score, setScore] = useState(0)
  return (
    <>
      <div>
        {name}: {score}
      </div>
      <button onClick={() => setScore(score + 1)}>+1</button>
    </>
  )
}

// ----------

// Do you think they are the same?
// ----- Approach 1
{
  isPlayerA ? <Counter name="A" /> : <Counter name="B" />
}

// ----- Approach 2
{
  isPlayerA && <Counter name="A" />
}
{
  !isPlayerA && <Counter name="B" />
}

The UI Tree

As you can see in the below picture, the rendering flow of React should be:

JSX –(React)–> UI trees –(React DOM)–> DOM

State is tied to a position in the tree

function Counter() {
  const [score, setScore] = useState(0)

  return <div>...</div>
}

return (
  <div>
    <Counter />
    <Counter />
  </div>
)

Preserves state

const [isFancy, setIsFancy] = useState(false);

 return (
  <div>
    {isFancy ? (
      <Counter isFancy={true} />
    ) : (
      <Counter isFancy={false} />
    )}
  </div>
  ...
)

=> Same component + Same position -> Preserve state

Different components at the same position reset state

const [isPaused, setIsPaused] = useState(false);

 return (
  <div>
    {isPaused ? (
      <p>See ya!</p>
    ) : (
      <Counter />
    )}
  </div>
  ...
)

=> Different component + Same position -> Reset the state of its entire subtree

Resetting state at the same position

By default, React preserves state of a component while it stays at the same position. But we have ability to reset the state.

Back to the example at the beginning of the article

// Approach 1
{
  isPlayerA ? <Counter name="A" /> : <Counter name="B" />
}

Option 1: Rendering component with different positions

{
  isPlayerA && <Counter name="A" />
}
{
  !isPlayerA && <Counter name="B" />
}

Option 2: Resetting state with a key (recommendation)

{
  isPlayerA ? <Counter name="A" key="A" /> : <Counter name="B" key="B" />
}

Reference