React-native-tab-view: Re render issue

Created on 12 Jan 2018  路  7Comments  路  Source: satya164/react-native-tab-view

Expected behaviour

Page returned for particular case in _renderScene should only render once.

Actual behaviour

I am using same component for all cases, i just change a text based on the users tab selection.
so my component renders as many times as i have cases i.e. 4 times in this case.

Code sample, screenshots

_renderScene = ({ route }) => {
      switch (route.key) {
        case '1':
          return (
            <PresetSettings
              type="Home"
            />
          );
        case '2':
          return (
            <PresetSettings
              type="Away"
            />
          );
        case '3':
          return (
            <PresetSettings
              type="Manual"
            />
          );
        case '4':
          return (
            <PresetSettings
              type="Eco"
            />
          );
        default:
          return null;
      }
    };

so my PresetSettings render function is called 4 times, instead of just one. and as i switch index the rerenders occur again 4 times.

What have you tried

if i dont use the same component and use different for all cases the issue disappears.
But my use case requires to use the same component but send a different type prop based on index.
How can i fix this ?

Most helpful comment

All 7 comments

@satya164 it suggests doing this

renderScene = ({ route }) => {
  switch (route.key) {
  case 'home':
    return <HomeComponent />;
  default:
    return null;
  }
}

which i am already doing in my case. Can u please elaborate on how i can resolve this re render ??
Any help will be much appreciated

it also says

and apply shouldComponentUpdate to prevent unnecessary re-renders

And where do we apply this mystical 'shouldComponentUpdate'..

I'm having this same issue. @sumesh1993 , did you figure it out?

@tobzy The problem is, that when you do return <HomeComponent />; it basically instantiates a new component, and therefore not what you want. You need to create the persistent component outside of the render function. I create my persistent components inside the constructor of the component which contains the tab view.

By shouldComponentUpdate he means that you need to use a 'PureComponent' for this to work since these components don't automatically rerender on state change. Hope this is enough help for you

for anyone else coming to this (old) issue via a google search, the way to do this in a functional component is to use React.memo- i.e. wrap your inline component inside it, or wrap it at export

Was this page helpful?
0 / 5 - 0 ratings

Related issues

karthikeyansundaram2 picture karthikeyansundaram2  路  3Comments

ahmedrowaihi picture ahmedrowaihi  路  3Comments

f6m6 picture f6m6  路  3Comments

ashusdn picture ashusdn  路  4Comments

QuentinBrosse picture QuentinBrosse  路  4Comments