본문 바로가기

React

[React 기본] PureComponent 실제로 해보기

PureComponent 개념

PureComponet는 이전의 props과 state를 비교하여 (가볍게 비교!!!! shallow !!) 진짜 필요한 컴포넌트만 업데이트 해주는 것 !

PureComponent에 대한 자세한 개념설명

 

[React 기본] PureComponent란 ? (Component, PureComponent차이)

pureComponent 하기 전에 알아야 할 개념 리액트의 데이터 하나 바뀐다고 계속되는 re-rendering 성능에 문제 없나요 ? 리액트는 state가 변화되면 전체 컴포넌트의 render 함수가 호출되는데, 단 한개라도

joannashin.tistory.com

 


PureComponent 실제로 적용해보기

import React, { PureComponent } from 'react';

class habitAddForm extends PureComponent {
	//...
}

export default habitAddForm;
적용방법은 간단하다. 기존에 Component였던 것을 PureComponent로 바꿔주기만 하면 된다.
하지만! 주의할 점은 개념설명에서도 나와있듯이 deep하게 변화를 감지하지 않는다.
stundent = {
  person1: {
      name:  'joanna',
      phone: '1234'
  }
}​

즉, student라는 객체가 통으로 바뀌지 않는 이상 안에 있는 person1이나 name의 값 등이 변경이 되어도 react는 감지하지 못한다는 뜻이다.

 

 


deep하게 변경 감지 못하는것 방어하기

기존 Component를 사용한 소스

import React, { Component } from 'react';

class Habit extends Component {
    handleIncrement = ( habit ) => {
      const habits = [...this.state.habits];
      const index = habits.findIndex(v => v.name === habit.name);
      habits[index].count = habits[index].count + 1;
      const count = this.state.count;

      this.setState({ 
        count: count + 1,
        habits,
      });
    };

    //...
}
Component는 데이터 감지가 잘 되어서 모든 컴포넌트를 render시켜주기 때문에 위의 소스는 이슈가 없다.

 

PureComponent를 사용한 소스

import React, { PureComponent } from 'react';

class Habit extends PureComponent {
	handleIncrement = ( habit ) => {
       const habits = this.state.habits.map(item => {
            if (item.name === habit.name) {
                return { ...habit, count: habit.count + 1};  //이거!! 새로운 객체 껍데기를 만들어서 덮어씌우기
            }

            return item;
        })
    }

    this.setState({ habits });

    //...
}
PureComponent는 데이터를 shallow 하게, 가볍게 감지하기 때문에 통으로 바꿔주어야한다.
따라서 변경이 필요한 부분은 기존 객체를 복사하여 변경이 필요한 count부분만 변경시키고, 나머지는 그대로 return 하여 새로운 배열을 만들어서 그걸 setState를 통해 state를 업데이트 시킨다.

 


정리

따라서 무조건 PureComponent로 바꿀 것이 아니라, 만약 계속해서 업데이트가 되는 컴포넌트라면 그냥 Component로 가는 것이 맞다고 한다. 그렇지 않다면(render가 다시 필요없다면) PureComponent로 바꿔주는것이 좋다.
반응형