I have simple React app, where I conditionally render two instances of the same component 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 components
</button>
{showFirst ? (
<SomeComponent text="I am the first" />
) : (
<SomeComponent text="I am the second" />
)}
</div>
);
}
This component has internal state: I increase a counter on a mouse click inside this component:
class SomeComponent extends React.Component {
state = {
count: 0
};
componentDidMount() {
console.log("mounted");
}
componentWillUnmount() {
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 components, but they share state. Why is that?
Here is a live demo to illustrate my point.
You need to add key prop to let react know its a different instance see your forked example
https://stackblitz.com/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With