Home > Back-end >  In React, When screen change, Component re-renders already rendered function
In React, When screen change, Component re-renders already rendered function

Time:11-29

I have a flatlist and I use it with memo.

Screen 1.js Component

<FlatList
data={props.cars.results}
renderItem={(item)=> <SinleRowMemo item={item}/>}
/>

In SingleRow.js component;

export const SingleRow=(props.item)=>{
return (
<TouchableOpacity onPress={()=>SomeFuncComesFromProps()}>
    <View>
          <Text>{props.car.brand}</Text>
    </View>
</TouchableOpacity>
export const SingleRowMemo=React.memo(SingleRow)

App.js

 <Route path={"/"} component={<Screen 1/>}/>
 <Route path={"/detail"} component={<Screen 2/>}/>
 <Route path={"/about"} component={<Screen 3/>}/>

The problem is that when I go to '/detail' screen and return to '/' page, the SingleRowMemo function re-run again and renders all rows that have been already rendered. How to fix this problem ? Thank you

CodePudding user response:

This cause react memo hook change your code as follows

const SingleRow=(props.item)=>{
return (
<TouchableOpacity onPress={()=>SomeFuncComesFromProps()}>
    <View>
          <Text>{props.car.brand}</Text>
    </View>
</TouchableOpacity>
export default SingleRow

CodePudding user response:

The memoization doesn't avoid the rerenders simply because the parameter is changing for each row. React.memo() is intended for cases where a component is rendered often with the same params and rendering is relatively expensive.

https://dmitripavlutin.com/use-react-memo-wisely/

  • Related