Ryder Brooks
Ryder Brooks

Reputation: 2119

React.js Component context of 'this'

I'm using reactjs and an es6 WeakMap to map state to a specific component. I'm doing this by using the this value of the component as the key in the WeakMap of the store associated with the component.

When a react component unmounts from the DOM and is then remounted, is the remounted component given a new this context?

I've deduced from the react component life cycle documentation that a new instance of the component is created on remount, but it's not explicitly stated as being the case. I'd appreciate it if someone with more experience with react could clarify this for me.

Also, if anyone believes that conceptually mapping components to state in the way I'm attempting to do is poor design please feel free to chime in.

Upvotes: 0

Views: 152

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22933

When a component is unmounted the instance is thrown away and will get garbage collected. When the component gets mounted again, it will be a new instance.

I'm not sure what your use case is, but I think that you can be fairly certain that this will always be the case, but it's not impossible to think that React would reuse instances as an optimization in the future.

Why do you need to keep state in a WeakMap instead of storing it inside a component higher up in the hierarchy?

Upvotes: 1

Related Questions