react re-rendering 방지(PureComponent)

IvanSelah·2021년 9월 2일
post-thumbnail
-------------------class--------------------------

import React, { Component } from "react;

class HabitAddForm extends Component {...}

------------------function------------------------

import React from "react";

const HabitAddForm = () => {...}

Class의 경우 변경 (Component -> PureComponent)
Function의 경우 (memo)

-------------------class--------------------------

import React, { PureComponent } from "react;

class HabitAddForm extends PureComponent {...};

------------------function------------------------

import React, { memo } from "react";

const HabitAddForm = memo(() => {...});

PureComponent는 props과 state안에 들어 있는 데이터, 최상위에 있는 데이터가 변하지 않으면

(전의 props 안에 있는 데이터와 얇은 비교를 하여 새로운 props의 경우만 false를 반환)

render 함수가 호출 되지 않는다. 즉, re-rendering을 하지 않습니다.

예시)

state = {
	number : [{ id : 1, count : 0}]
};

const number = this.state.number.map(item => {
	return item;
})

this.state.number === number(map은 새로운배열 반환); 참조값이 다르므로 false 입니다.
하지만 각 number안에 count의 참조값은 같기 때문에 True 입니다.

❗ 주의

동일한 오브젝트를 사용하고 그 안에 값만 변경된다면 적용되지 않습니다.
(동일한 오브젝트는 참조값도 동일하므로)

✅ 적용
동일한 오브젝트를 사용하지 않고 새로운 오브젝트를 새로만들어 사용하면 참조값이 달라진다.

const number = this.state.number.map(item => {
	return {...item, count : item.count + 1};
});
this.setState({ number })
profile
{IvanSelah : ["꿈꾸는", "끊임없이 노력하는", "프론트엔드 개발자"]}

0개의 댓글