Understanding Keys, Props, and Component Identity in React
Keys in React donât just help with listsâthey define component identity. This post explains how the same component can either preserve or reset its state depending on its key, even when props change.
When I first learned React, I thought props were the main thing that controlled how a component behaves.
But after digging deeper, I realized something more important:
Props affect what a component shows
This distinction becomes very clear when you start dealing with rendering, re-rendering, and state.
The Scenario That Changes Everything
Consider this:
function App() {
const [toggle, setToggle] = React.useState(false)
return (
<>
<button onClick={() => setToggle(!toggle)}>
Toggle
</button>
{toggle
? <Test key="A" value={1} />
: <Test key="A" value={2} />
}
</>
)
}At first glance, it feels like switching between two different components.
But React doesnât see it that way.
Same Key, Different Props
Even though value changes:
<Test key="A" value={1} />
<Test key="A" value={2} />React sees:
Same component type + same keySo it decides:
- Reuse the same component instance
- Keep its state
- Just re-run the function with new props
What Actually Happens
Inside the component:
function Test({ value }) {
console.log("render", value)
return <h1>{value}</h1>
}Youâll see:
render 1
render 2The component re-renders â but it is not recreated.
Now Change One Thing
{toggle
? <Test key="A" value={1} />
: <Test key="B" value={1} />
}Now the key changes.
Same Props, Different Key
Even though value is still 1, React sees:
"A" â "B"So it decides:
- Destroy the old component
- Create a new one
- Reset its state
Why This Happens
React uses two things to identify a component:
Component type + keyIf both match:
- Same instance
If either changes:
- New instance
The Key Insight
Props control rendering, but keys control identity.
Why This Matters for State
Imagine this:
function Test({ value }) {
const [count, setCount] = React.useState(0)
return (
<div>
<p>value: {value}</p>
<p>count: {count}</p>
</div>
)
}Same key:
<Test key="A" value={1} />
<Test key="A" value={2} />valueupdatescountstays
Different key:
<Test key="A" value={1} />
<Test key="B" value={1} />countresets to 0
The Real Mental Shift
At first, itâs easy to think:
âProps define the componentâ
But in React:
- Props = data
- Key = identity
- State = memory
And identity is what determines whether React:
- reuses
- or recreates
A Practical Use Case
You can use keys intentionally to reset state:
<Test key={userId} />When userId changes:
- component resets
- state resets
This is not a hack â itâs a feature.
Final Takeaway
The most important realization is this:
React doesnât care if props are the same â it cares if the identity is the same.
Once you understand that keys define identity, a lot of React behavior stops feeling random and starts feeling predictable.