Preserving and Resetting State·续1
h1 {
font-size: 18px;
}
.counter {
width: 100px;
text-align: center;
border: 1px solid gray;
border-radius: 4px;
padding: 20px;
margin: 0 20px 20px 0;
}
.hover {
background: #ffffd8;
}
Currently, when you change the player, the score is preserved. The two Counters appear in the same position, so React sees them as the same Counter whose person prop has changed.
But conceptually, in this app they should be two separate counters. They might appear in the same place in the UI, but one is a counter for Taylor, and another is a counter for Sarah.
There are two ways to reset state when switching between them:
- Render components in different positions
- Give each component an explicit identity with
key
Option 1: Rendering a component in different positions
If you want these two Counters to be independent, you can render them in two different positions:
import { useState } from 'react';
export default function Scoreboard() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<div>
{isPlayerA &&
<Counter person="Taylor" />
}
{!isPlayerA &&
<Counter person="Sarah" />
}
<button onClick={() => {
setIsPlayerA(!isPlayerA);
}}>
Next player!
</button>
</div>
);
}
function Counter({ person }) {
const [score, setScore] = useState(0);
const [hover, setHover] = useState(false);
let className = 'counter';
if (hover) {
className += ' hover';
}
return (
<div
className={className}
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
<h1>{person}'s score: {score}</h1>
<button onClick={() => setScore(score + 1)}>
Add one
</button>
</div>
);
}
h1 {
font-size: 18px;
}
.counter {
width: 100px;
text-align: center;
border: 1px solid gray;
border-radius: 4px;
padding: 20px;
margin: 0 20px 20px 0;
}
.hover {
background: #ffffd8;
}
- Initially,
isPlayerAistrue. So the first position containsCounterstate, and the second one is empty. - When you click the "Next player" button the first position clears but the second one now contains a
Counter.
Initial state
Clicking "next"
Clicking "next" again
Each Counter's state gets destroyed each time it's removed from the DOM. This is why they reset every time you click the button.
This solution is convenient when you only have a few independent components rendered in the same place. In this example, you only have two, so it's not a hassle to render both separately in the JSX.
Option 2: Resetting state with a key
There is also another, more generic, way to reset a component's state.
You might have seen keys when rendering lists. Keys aren't just for lists! You can use keys to make React distinguish between any components. By default, React uses order within the parent ("first counter", "second counter") to discern between components. But keys let you tell React that this is not just a first counter, or a second counter, but a specific counter--for example, Taylor's counter. This way, React will know Taylor's counter wherever it appears in the tree!
In this example, the two <Counter />s don't share state even though they appear in the same place in JSX:
import { useState } from 'react';
export default function Scoreboard() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<div>
{isPlayerA ? (
<Counter key="Taylor" person="Taylor" />
) : (
<Counter key="Sarah" person="Sarah" />
)}
<button onClick={() => {
setIsPlayerA(!isPlayerA);
}}>
Next player!
</button>
</div>
);
}
function Counter({ person }) {
const [score, setScore] = useState(0);
const [hover, setHover] = useState(false);
let className = 'counter';
if (hover) {
className += ' hover';
}
return (
<div
className={className}
onPointerEnter={() => setHover(true)}
onPointerLeave={() => setHover(false)}
>
<h1>{person}'s score: {score}</h1>
<button onClick={() => setScore(score + 1)}>
Add one
</button>
</div>
);
}
h1 {
font-size: 18px;
}
.counter {
width: 100px;
text-align: center;
border: 1px solid gray;
border-radius: 4px;
padding: 20px;
margin: 0 20px 20px 0;
}
.hover {
background: #ffffd8;
}
Switching between Taylor and Sarah does not preserve the state. This is because you gave them different keys:
{isPlayerA ? (
<Counter key="Taylor" person="Taylor" />
) : (
<Counter key="Sarah" person="Sarah" />
)}
Specifying a key tells React to use the key itself as part of the position, instead of their order within the parent. This is why, even though you render them in the same place in JSX, React sees them as two different counters, and so they will never share state. Every time a counter appears on the screen, its state is created. Every time it is removed, its state is destroyed. Toggling between them resets their state over and over.
[!NOTE]
Remember that keys are not globally unique. They only specify the position within the parent.
Resetting a form with a key
Resetting state with a key is particularly useful when dealing with forms.
In this chat app, the <Chat> component contains the text input state:
```js src/App.js import { useState } from 'react'; import Chat from './Chat.js'; import ContactList from './ContactList.js';
export default function Messenger() { const [to, setTo] = useState(contacts[0]); return (
const contacts = [ { id: 0, name: 'Taylor', email: 'taylor@mail.com' }, { id: 1, name: 'Alice', email: 'alice@mail.com' }, { id: 2, name: 'Bob', email: 'bob@mail.com' } ];
```js src/ContactList.js
export default function ContactList({
selectedContact,
contacts,
onSelect
}) {
return (
<section className="contact-list">
<ul>
{contacts.map(contact =>
<li key={contact.id}>
<button onClick={() => {
onSelect(contact);
}}>
{contact.name}
</button>
</li>
)}
</ul>
</section>
);
}
```js src/Chat.js import { useState } from 'react';
export default function Chat({ contact }) { const [text, setText] = useState(''); return (
