Home > database >  How to avoid re rendering in react native?
How to avoid re rendering in react native?

Time:10-13

I'm trying to avoid re-rendering unnecessary components
For example:

const[ValueState,SetValueState]=useState(5); //hook

<View>
 <Text>{ValueState}</Text>
 <View>
  {
   [...Array(3)].map((index,el)=>{
    return (<View><Text>Hello there</Text></View>)
   })
  }
 </View>
</View>

here every time I change the value of ValueState the entire map() segment also gets re-rendered
how do I avoid this and make the map() segment only render 1 time?

CodePudding user response:

It depends on what the function you don't want to re-render depends on. In this case, your array and map function do not depend directly to ValueState.

One way to achieve 1 re-render is using React.memo

Example to render map function only once

import React, { useState } from "react";
import { View, Text, TouchableOpacity } from "react-native";



const ArrayMapSection = React.memo(()=> {
  console.log("ArrayMapSection rendered")
  return  [...Array(3)].map((index,el)=>{
    return (<View><Text>Hello there</Text></View>)
   });
})

const App = () => {
const [ValueState,SetValueState]=useState(5); //hook

return(
<View>
 <Text>{ValueState}</Text>

 <TouchableOpacity onPress={()=>SetValueState(Math.random())}>Press to state update</TouchableOpacity>
 <View>
  <ArrayMapSection />
 </View>
</View>

)


};

export default App;

If you run this program, you would see ArrayMapSection renderedonly once in the console. Now try to change the ValueState by pressing on Press to state update. The ArrayMapSection won't re-render because React.memo only re-renders if props changes

More info: https://reactjs.org/docs/react-api.html#reactmemo

CodePudding user response:

Create a custom react component that takes the array as a prop and maps it to other components.

That way the component is only rerenderd if the array prop changes.

Code example:

const[ValueState,SetValueState]=useState(5);

<View>
 <Text>{ValueState}</Text>
 <CustomList array={[1,2,3]} />
</View>

export const CustomList = (array) => {
    return (
        <>
          {
            array.map((index,el)=>{
                return (<View><Text>Hello there</Text></View>)
            })
          }
        <\>
    )
}
  • Related