Reputation: 2441
I have 2 tabs in my React Native application. First one renders female names, second renders male names. I have a component <List names={[]} />
and I pass into it an array of names based on the active tab. Like that:
render() {
const gender = this.props.isFemaleTabActive ? 'female' : 'male';
return <List names={this.props.names[gender]} />;
}
<List>
component uses SectionList
to show these names, but every time when active tab is changing it causes a delay in showing data and highlighting an active tab.
But It works fine if I use react-loadable
and do it like that:
const FemaleNamesList = Loadable({
loader: () => import('../components/List'),
loading: () => <Text>Loading...</Text>
});
const MaleNamesList = Loadable({
loader: () => import('../components/List'),
loading: () => <Text>Loading...</Text>
});
render() {
const gender = this.props.isFemaleTabActive ? 'female' : 'male';
return isFemaleTabActive ? (
<FemaleNamesList names={this.props.names[gender]} />
) : (
<MaleNamesList names={this.props.names[gender]} />
);
}
Can you help me to understand why in that case it works fine and maybe there is any other ways to optimize it.
Upvotes: 0
Views: 955
Reputation: 8418
1st method only updates data on existing/mounted component while 2nd entirely replaces 2 different components.
In first case component has to compare data to detect changes (optimize items rerendering) - it can be costly operation for bigger sets. When component is created as a new instance it's not checked.
Probably (didn't checked) similiar effect (speedup) can be achieved when <List />
will be surrounded within different (dumb, just rendering children) components to fool react with different tree structure, sth like:
render() {
const gender = this.props.isFemaleTabActive ? 'female' : 'male';
return isFemaleTabActive ? (
<DumbA><List names={this.props.names[gender]} /></DumbA>
) : (
<DumbB><List names={this.props.names[gender]} /></DumbB>
);
}
Probably the easiest way to force component exchange would be using key
property:
render() {
const gender = this.props.isFemaleTabActive ? 'female' : 'male';
return <List key={gender} names={this.props.names[gender]} />;
}
Of course this is not any kind of optimization.
Upvotes: 1