TIW 7월 6일 - React PureComponent 예제

ktseo41·2020년 7월 5일
0

TodayIWrote

목록 보기
5/5
post-thumbnail
import React, { useState } from "react";
import "./styles.css";

// 클래스형 컴포넌트이나 shouldComponentUpdate를 작성해 props, state를 비교
class Welcome3 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.name !== nextProps.name) return true;
    if (this.state.count !== nextState.count) return true;
    return false;
  }

  render() {
    console.log("Welcome3", this.state.count, this.props.name);
    return (
      <div>
        <div>{this.props.name}</div>
        <div>{this.state.count}</div>
        <button
          onClick={() => {
            this.setState(state => {
              return { count: state.count + 1 };
            });
          }}
        >
          +
        </button>
      </div>
    );
  }
}

// PureComponent
class Welcome2 extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    console.log("Welcome2", this.state.count, this.props.name);
    return (
      <div>
        <div>{this.props.name}</div>
        <div>{this.state.count}</div>
        <button
          onClick={() => {
            this.setState(state => {
              return { count: state.count + 1 };
            });
          }}
        >
          +
        </button>
      </div>
    );
  }
}

// 일반적인 컴포넌트
function Welcome(props) {
  const [count, setCount] = useState(0);

  console.log("Welcome", count, props.name);

  return (
    <div>
      <div>{props.name}</div>
      <div>{count}</div>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        +
      </button>
    </div>
  );
}

export default function App() {
  const [names, setNames] = useState(["sara", "james", "porter"]);
  const [inputText, setInputText] = useState("");

  const textInput = evt => {
    setInputText(evt.target.value);
  };

  const addNames = () => {
    setNames([...names, inputText]);
  };

  return (
    <div className="App">
      <div>{names.reduce((a, b) => `${a} ${b}`)}</div>
      <input type="text" onChange={textInput} value={inputText} />
      <button onClick={addNames}>go</button>
      {names.map(name => {
        return <Welcome name={name} />;
      })}
      {names.map(name => {
        return <Welcome2 name={name} />;
      })}
      {names.map(name => {
        return <Welcome3 name={name} />;
      })}
    </div>
  );
}

0개의 댓글