React-native: shouldComponentUpdate (Render ของเท่าที่จำเป็น)

Anupat Ruangsuwan
Aug 22, 2017 · 2 min read

ผมได้สร้าง React Class ข้างในประกอบไปด้วย State กับ Render ดังนี้นะครับ

ในส่วนของ State

this.state = {
active: 0,
data: ['a','b','c','d','e','f','g','h','h','j']
}

ในส่วนของ Render

render() {
const { data, active } = this.state

return (
<View style={styles.container}>
{ data.map((currentValue, index) => {
return (
<SCUComponent
key={index}
currentValue={currentValue}
index={index}
showText={active === index}
onPressAction={(resIndex) =>
this.setState({ active: resIndex })
} />
)
})
}
</View>
);
}

และ ผมได้สร้าง Component ที่ชื่อว่า SCUComponent ประกอบไปด้วย

render() {
const { currentValue, index, showText } = this.props
console.log(" Render ", index);

return (
<TouchableOpacity
onPress={() => this.props.onPressAction(index)} >
<Text>{currentValue} : {( showText ? 'ACTIVE !!!' : 'NON ACTIVE')}

</Text>
</TouchableOpacity>
);
}

เราได้ console.log เพื่อดูว่า Render มีการเรียกใช้งานไหม ผลปรากฏว่า

เรากดแค่ตัวเดียว แต่ทำไมต้อง Render ใหม่ทั้งหมด

แล้วถ้ามีเป็น 1000++ ตัวหล่ะ !!! แอพไม่ค้างไปเลยหรอ

shouldComponentUpdate() ช่วยคุณได้

เพียงแค่คุณนำ shouldComponentUpdate ไปไว้ใน React component ของคุณ แล้วบอกมันว่า ถ้า props ที่เข้ามาใหม่นั้น เป็นตัวเดิม ก็ไม่ต้องให้เรียก Render ซะนะ จะได้ไม่ช้า

หลังจากที่ผมได้เพิ่ม shouldComponentUpdate หน้าตาก็จะประมาณนี้ครับ

shouldComponentUpdate(nextProps, nextState){
const { showText } = this.props
if (showText !== nextProps.showText) {
return true
}
return false
}
render() {
const { currentValue, index, showText } = this.props
console.log(" Render ", index);

return (
<TouchableOpacity
onPress={() => this.props.onPressAction(index)} >
<Text>{currentValue} : {( showText ? 'ACTIVE !!!' : 'NON ACTIVE')}

</Text>
</TouchableOpacity>
);
}

เรามาดูกันว่าจะ Render กี่ครั้ง

ในการ Click 1 ครั้งนั้น จะมีการ Render เพียง 2 ครั้ง 2 ครั้งนั้นมาจาก

  1. เปลี่ยน Active ให้เป็น Non Active
  2. เปลี่ยน Non Active ให้เป็น Active

Ref. https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

ขออภัย สำหรับท่านที่รู้อยู่แล้วนะครับ

ขอบคุณครับ ^^

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade