Reputation: 26273
In the example below, I'm seeing Child
get unmounted and re-mounted on every ComponentA
render. None of the other components in the tree are re-mounted.
class ComponentA extends Component {
renderChild() {
return <Child />;
}
render() {
return <ComponentB>{this.renderChild()}</ComponentB>;
}
}
class ComponentB extends Component {
render() {
return <ComponentC passthruChild={() => children} />;
}
}
class ComponentC extends Component {
render() {
const PassedThruChild = this.props.passthruChild;
return <div><PassedThruChild /></div>;
}
}
Why is this happening, and how can I make it not happen?
Upvotes: 0
Views: 179
Reputation: 56
This is entirely speculative but I think it could be something along the lines of: when ComponentA renders, a new instance of Child gets returned by this.renderChild(). This instance is different from some cached instance which results in the cached child being replaced with the new instance. Cached one being unmounted and the new one being mounted.
In the other two cases the pass thru child could be a reference to the same object across multiple renders.
I think you should be able to check and see if they are the same object or a different object using the dev tools.
I can't post a reply to your comment since I don't have 50 points so I will answer here:
If you save were to cache the returned object from this.renderChild() so that you're not creating a new one every time the function is called you could probably make it work.
Upvotes: 1