I have simple React app, where I conditionally render two instances of the same ponent based on the value of a boolean variable:
export default function App() {
const [showFirst, setShowFirst] = useState(true);
return (
<div>
<button type="button" onClick={() => setShowFirst(show => !show)}>
Switch between ponents
</button>
{showFirst ? (
<SomeComponent text="I am the first" />
) : (
<SomeComponent text="I am the second" />
)}
</div>
);
}
This ponent has internal state: I increase a counter on a mouse click inside this ponent:
class SomeComponent extends React.Component {
state = {
count: 0
};
ponentDidMount() {
console.log("mounted");
}
ponentWillUnmount() {
console.log("unmounting");
}
render() {
return (
<div
style={{
display: "flex",
flexDirection: "column",
border: "2px solid green",
padding: 8
}}
>
{this.props.text}
<button
onClick={() =>
this.setState(({ count }) => ({
count: count + 1
}))
}
>
increase counter
</button>
{this.state.count}
</div>
);
}
}
I expected the 'count' state variable inside SomeComponent to have two different values inside the two ponents, but they share state. Why is that?
Here is a live demo to illustrate my point.
I have simple React app, where I conditionally render two instances of the same ponent based on the value of a boolean variable:
export default function App() {
const [showFirst, setShowFirst] = useState(true);
return (
<div>
<button type="button" onClick={() => setShowFirst(show => !show)}>
Switch between ponents
</button>
{showFirst ? (
<SomeComponent text="I am the first" />
) : (
<SomeComponent text="I am the second" />
)}
</div>
);
}
This ponent has internal state: I increase a counter on a mouse click inside this ponent:
class SomeComponent extends React.Component {
state = {
count: 0
};
ponentDidMount() {
console.log("mounted");
}
ponentWillUnmount() {
console.log("unmounting");
}
render() {
return (
<div
style={{
display: "flex",
flexDirection: "column",
border: "2px solid green",
padding: 8
}}
>
{this.props.text}
<button
onClick={() =>
this.setState(({ count }) => ({
count: count + 1
}))
}
>
increase counter
</button>
{this.state.count}
</div>
);
}
}
I expected the 'count' state variable inside SomeComponent to have two different values inside the two ponents, but they share state. Why is that?
Here is a live demo to illustrate my point.
Share Improve this question asked Jan 10, 2021 at 15:10 handrishandris 2,1098 gold badges28 silver badges44 bronze badges1 Answer
Reset to default 9You need to add key
prop to let react know its a different instance see your forked example
https://stackblitz./edit/react-g7a6vr?file=src/App.js
The official documentation clarifies this perfectly:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.