3

React updates its component tree based on the names of the elements in that tree.

For example:

<div>
  <MyComponent/>
</div>

And:

<div>
  <MyComponent enabled/>
</div>

...results in React using the same <MyComponent> instance (because the component name did not change). This is very useful because it ensures that internal state within the component instance persists.

See the documentation for more details.

My question: "Is there a way to force a new instance to be created in certain circumstances?"

So rather than using the same MyComponent instance, I would like a new one to be instantiated if (let's say) prop 'x' has changed.

David
  • 3,392
  • 3
  • 36
  • 47
sookie
  • 2,437
  • 3
  • 29
  • 48
  • Possible duplicate of [How to force remounting on React components?](https://stackoverflow.com/questions/35792275/how-to-force-remounting-on-react-components) – imjared Oct 11 '18 at 16:54

1 Answers1

4

Untested, but I think you could trick React and add the prop as a key on the component.

<div>
  <MyComponent enabled key={enabled.toString()} />
</div>

Since you're familiar with the reconciliation docs, I imagine you know what keys do already ;)

imjared
  • 19,492
  • 4
  • 49
  • 72