본문 바로가기

Front/React

React - PureComponent & memo

 

React 공식 reference문서에서 발췌

 

PureComponent가 Component와 다른점

shouldComponentUpdate()의 구현이 되어있다.

해당 컴포넌트의 props와 state가 바뀌어서 업데이트가 필요하다면 true를 리턴하고,

바뀌지 않았다면 false를 리턴해서 컴포넌트를 업데이트 하지 않는다.

 

Shallow Comparison (얕은 비교)

props와 state를 비교할때, 얕은 비교를 한다는 것은 reference를 비교한다는 것이다.

객체를 가지고 있다면 그 객체가 가지고 있는 어떤 데이터가 변경되더라도

객체가 변경되지 않았으니 같은 객체로 본다.

 

 

 

출처

ko.reactjs.org/docs/react-api.html#reactpurecomponent

 


 

얕은 비교를 위한 데이터 수정 방법

객체의 데이터 값만 수정하는 것이 아니라, 수정된 값으로 객체를 새로 만들어 교체한다.

 

------------------------------------------------------------------------------------------

// plus 버튼을 눌렀을 때 데이터가 증가하는 함수

 

handleIncrement = (id) => {

  let habits = [...this.state.habits];

 

  habits = habits.map(item => {

    if(item.id === id){

      // item.count = item.count+1;   //직접적으로 객체의 데이터를 수정하면 얕은 비교에서는 객체의 변화로 감지하지않음.

      return {...item, count: item.count+1};   //deconstructing Object : {...item}과 같이 데이터는 똑같이 새로 만들어진 오브젝트.

    }

    return item;

  });

 

this.setState({habits});

}

------------------------------------------------------------------------------------------

 


 

memo

함수형 컴포넌트에서 PureComponent와 같은 역할을 한다.

props와 state가 변하지 않았을 때는 컴포넌트 업데이트를 하지 않도록 체크한다.

 

------------------------------------------------------------------------------------------

import React, { memo } from 'react';

 

const habitAddForm = memo((props) => {

 

  const inputRef = React.createRef();

  const handleAdd = event => {

    event.preventDefault();

    const name = inputRef.current.value;

    name && props.onAdd(name);

    inputRef.current.value = '';

  }

 

  return (

    <form className="add-form" onSubmit={handleAdd}>

    <input type="text" className="add-input" placeholder="Habit" ref={inputRef} />

    <button className="add-button" type="submit">Add</button>

    </form>

    );

 

});

 

export default habitAddForm;

------------------------------------------------------------------------------------------

 

 

 

 

출처

ko.reactjs.org/docs/react-api.html#reactmemo