[React]class에서 성능향상(shouldComponentUpdate, PureComponent)

2021. 8. 31. 06:16·React
const React = require('react');

class Test extends React.Component {
  state = {
    counter: 0
  }
  
  onClick = () => {
    this.setState({})
  }
  render() {
    return (
      <div>
        <button onClick={this.onClick}>클릭</button>
      </div>
    )
  }
}

module.exports = Test;

위의 코드를 실행한 결과이다. 버튼을 누를 때마다 불필요하게 렌더링이 되어버린다.

해결방법1. shouldComponentUpdate

const React = require('react');

class Test extends React.Component {
  state = {
    counter: 0
  }
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    if (this.state.counter !== nextState.counter) {
      return true
    }
    return false
  }
  onClick = () => {
    this.setState({})
  }
  render() {
    console.log('렌더링')
    return (
      <div>
        <button onClick={this.onClick}>클릭</button>
      </div>
    )
  }
}
module.exports = Test;

위의 방법이 귀찮다면 아래의 PureComponent를 활용하는 것을 추천한다.

 

해결방법 2. PureComponent

const React = require('react');

class Test extends React.PureComponent {
  state = {
    counter: 0
  }
  onClick = () => {
    this.setState({})
  }
  render() {
    return (
      <div>
        <button onClick={this.onClick}>클릭</button>
      </div>
    )
  }
}
module.exports = Test;

PureComponent는 state가 바뀌었는지 아닌지를 보고 판단한다.

하지만, PureComponent의 단점은 객체나 배열과 같은 참조관계가 있는 구조일때는 바뀐것인지 아닌지 판단하기 힘들다.

 

'React' 카테고리의 다른 글

JWT를 통한 회원 인증 시스템 구현하기 - 1  (0) 2022.06.06
state, props  (0) 2021.10.29
'react-dom' / JSX  (0) 2021.10.26
Class Component VS Function Component  (0) 2021.10.26
React vs Vue  (0) 2021.08.26
'React' 카테고리의 다른 글
  • state, props
  • 'react-dom' / JSX
  • Class Component VS Function Component
  • React vs Vue
JoyYellow
JoyYellow
  • JoyYellow
    JoyYellow
    JoyYellow
  • 전체
    오늘
    어제
    • 분류 전체보기 (128)
      • Vue (7)
      • React (10)
      • 알고리즘 풀이 (29)
      • 타입스크립트 (2)
      • Microsoft (4)
      • TIL(Today I Learned) (16)
      • Devops (4)
      • CS(Computer Science) (2)
      • Spring (1)
      • Incomplete (0)
      • JS소스모듈 (10)
      • TDD (2)
      • 스프링부트 (0)
      • CSS (8)
      • Next.js (0)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    개발자북클럽
    노개북
    노마드코더
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
JoyYellow
[React]class에서 성능향상(shouldComponentUpdate, PureComponent)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.