Estoy tratando de evitar volver a renderizar componentes innecesarios
Por ejemplo:
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> aquí, cada vez que cambio el valor de ValueState el segmento completo del mapa () también se vuelve a representar
¿Cómo evito esto y hago que el segmento map() solo se represente 1 vez?
Depende de qué depende la función que no desea volver a renderizar. En este caso, su matriz y su función de mapa no dependen directamente de ValueState .
Una forma de lograr 1 renderizado es usando React.memo
Ejemplo para representar la función de mapa solo una vez
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; Si ejecuta este programa, verá que ArrayMapSection rendered solo una vez en la consola. Ahora intente cambiar el ValueState presionando Press to state update . ArrayMapSection no se volverá a renderizar porque React.memo solo se vuelve a renderizar si los accesorios cambian
Más información: https://reactjs.org/docs/react-api.html#reactmemo
Cree un componente de reacción personalizado que tome la matriz como accesorio y la asigne a otros componentes.
De esa manera, el componente solo se vuelve a renderizar si cambia la propiedad de la matriz.
Ejemplo de código:
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>) }) } <\> ) }