Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

리액트 정리

[React] 웹게임 3. 숫자야구 // 최적화(class) - shouldComponentUpdate & PureComponent 본문

리액트/웹게임

[React] 웹게임 3. 숫자야구 // 최적화(class) - shouldComponentUpdate & PureComponent

버그킴 2020. 1. 31. 13:32

리액트가 멍청해서

setState만 걸어놓으면 무조건 렌더링한다고 함.

(따라서 render()안에 setState걸면 안됨! 무제한으로 렌더 돌기 때문에.. )

 

 

최적화: 

 

처음 하시는 분들이 많이 안쓰시던데.. 나중에 성능에 중요해요 꼭 최적화를 하세요 라고

 

 

1. shouldComponentUpdate

그래서 어떤 조건부로 렌더링시켜주기.

state, props가 바뀌었을 때 원하는 것만 렌더링 다시 해줄 수 있다. 

import React, { Component } from 'react'

class Test extends Component {
  state = {
    counter: 0,
  };

  // 최적화. 현재의 카운터와 미래의 카운터가 다르면 렌더링 하고 아니면 안함
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    if(this.state.counter !== nextState.counter) {
      return true;
    }
    return false;
  }

  onClick = () => {
    this.setState({})
  }

  render() {
    console.log('렌더링', this.state);
    
    return(
      <>
        <button onClick={this.onClick}>클릭</button>
      </>
    )
  }
}

export default Test;

2. PureComponent

shouldComponentUpdate기능이 들어있음. 단, 새로운 배열 || 객체의 경우에는 얘도 알아차리지 못한다.

import React, { PureComponent } from 'react'

class Test extends PureComponent {
  state = {
    counter: 0,
    string: 'hello',
    number: 1,
    boolean: true,
    object: {a: 'b', c: 'd'}, // 알아차리지 못한다
    array: [1,2] // 이것도 
  };

  // 새로운 객체나 배열을 만들어서 리액트가 state다른것 알아차리고 렌더링 하도록 해주기
  onClick = () => {
    this.setState((prevState)=>{
      return {
        array: [...prevState.array, prevState.number]
      }
    })
  }

  render() {
    console.log('렌더링', this.state);
    
    return(
      <>
        <button onClick={this.onClick}>클릭</button>
      </>
    )
  }
}

export default Test;

Try.jsx

import React, { PureComponent } from 'react'

class Try extends PureComponent {
  render() {
    const {tryInfo} = this.props;
    return (
      <li>
        <div>{tryInfo.try} </div>
        <div>{tryInfo.result} </div>
      </li>
    );
  }
}


export default Try;

NumberBaseball.jsx props 떨궈주는 리턴부분

      <ul>
        {tries.map((v, i) => (
          <Try key={`${i + 1}차 시도 : ${v.try}`} tryInfo={v} />
        ))}
      </ul>

 

 

그럼 이제 React Dev Tool에서 번쩍거리지 않음 

빨간색일수록 심각한 것인데요

 

객체 안에 배열, 이런식으로 쓰지 말고

props를 이용해서 컴포넌트를 잘게 쪼개야 PureComponent 기능을 편리하게 사용할 수 있음. 

그렇다고 해서 무조건 쪼개면 안됨. 특정 state가 바뀌어도 렌더링을 안되게 할 수 있는 기능 (shouldComponentUpdate)도 사용할 수 있음.