Bug: Identical component in ternary does not rerender with initial state values set via props

This issue has been tracked since 2022-09-05.

React version: 18.0.0

Steps To Reproduce

  1. Take any component that makes use of useState with an initial value set via props, i.e. useState(props.myInitialValue)
  2. render two of these components via a ternary in a parent component, with differing prop values
  3. Toggling the ternary value to toggle which instance of the component should be shown
  4. No matter how many times you toggle which component is shown, the values of the first rendered component are used

Link to code example: https://codesandbox.io/s/hardcore-thunder-mennyr?file=/src/App.tsx

The current behavior

No matter which component is shown (how many times the toggle button is clicked), the originally rendered props of the component are shown.

The expected behavior

In my provided example, I expect true and "World" to be shown on the screen after toggling which component to render.

My guess is that React is somehow caching or 'seeing' the same component, despite the change in the prop values to said component. I also understand ternaries to render components are a topic of debate, but nevertheless, it is still valid JSX and I expect the expected behavior as described to occur.

princefishthrower wrote this answer on 2022-09-05

Update: adding a key prop to each of the components in the ternary statement resolves this issue. However, if this is the case (and perhaps not directly a 'bug') then I believe a warning should be added to the linter similar to the key warning for items rendered in a list.

rickhanlonii wrote this answer on 2022-09-06

This is expected, albeit sometimes surprising, behavior because it's the component's position in the tree, not the JSX markup, that matters to React. Using a key is the right way to tell react that the component is different, even though it's in the same position. I'm not sure how a lint rule would work here since it would warn in valid use cases.

Check out the new docs for a better explanation: https://beta.reactjs.org/learn/preserving-and-resetting-state#same-component-at-the-same-position-preserves-state

More Details About Repo
Owner Name facebook
Repo Name react
Full Name facebook/react
Language JavaScript
Created Date 2013-05-24
Updated Date 2022-10-03
Star Count 195560
Watcher Count 6648
Fork Count 40508
Issue Count 1111

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date