TIL_68_Hook

JIEUN·2021년 4월 19일
0
post-thumbnail

생활코딩 Hook

// App.js

let classStyle = 'color:red';
class ClassComp extends React.Component{
  state = {
    number:this.props.initNumber
    date:(new Date()).toString()
  }

  componentWillMount() {
    console.log('%cclass => componentWillMount', classStyle);
  }

  componentDidMount() {
    console.log('%cclass => componentDidMount', classStyle);
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('%cclass => shouldComponentUpdate', classStyle);
    return true;
}
  componentWillUpdate(nextProps, nextState) {
    console.log('%cclass => componentWillUpdate', classStyle);
}

  componentDidUpdate(nextProps, nextState) {
    console.log('%cclass => componentDidUpdate', classStyle);
}
//상태가 바뀌게 되면 상태가 위치하고 있는 
//컴퍼넌트의 랜더 메소드가 호출될 것.
//componentWillMount -> render -> componentDidMount -> 
//shouldComponentUpdate -> componentWillUpdate -> render -> 
//componentDidUpdate 순으로 호출이 됨.

  render(){
  console.log('%cclass => render', classStyle);
//컴퍼넌트 윌마운트가 호출된 다음에 렌더가 호출되는 것을 콘솔을 통해 확인할 수 있다.
//componentWillMount -> render -> componentDidMount 순으로 호출되는 것을 콘솔을 통해 확인할 수 있다.

    return (
      <div className="container">
        <h2>class style component<h2>
        <p>Number : {this.state.number}</p>
        <p>Date : {this.state.date}</p>
        <input type="button" value="random" onClick={
         function() {
           this.setState({number:Math.random()})
         }.bind(this)
        }></input>
         <input type="button" value="date" onClick={
         function() {
           this.setState({date:(new Date()).toString()})
           }.bind(this)
         }</input>
      </div>
   )
 } 
}

export default App;

클래스 방식은 라이프사이클에 따라서 정해진 메소드에 따라 원하는 타이밍에 원하는 어떤 코드를 호출할 수 있다.

// App.js
import React {useState, useEffect} from 'react';
import './App.css';

function App() {
  return (
    <div className="container">
      <h1>Hello World</h1>
      <FuncComp initNumber={2}></FuncComp>
      <ClassComp initNumber={2}></ClassComp>
    </div>
  );
}

let funcStyle = 'color:blue';
let funcId = 0;

function FuncComp(props) {
  let numberState = useState(props.initNumber);
  let number = numberState[0];
  let setNumber = numberState[1];

  //let dateState = useState((new Date().toString()));
  //let _date = numberState[0];
  //let setNumber = numberState[1];

  let [_date, setDate] = useState((new Date()).toString());

  //side effect
  useEffect(function(){
  console.log('%cfunc => useEffect (componentDidMount & componentDidUpdate)'+ (++funcId), funcStyle);
  document.title = number + ' : ' + _date;
});
//페이지를 리로드 하면, func => render 1 작업이 완전히 끝난 다음에 
//func => useEffect 2 가 호출.
//화면상에 랜덤을 클릭하게 되면 
//func => render 3 -> func => useEffect 4 가 호출됨.
//유즈 이팩트라고 하는 훅은 웹페이지가 처음으로 랜더가 끝났을 때 
//실행이 되고 랜더가 실행될 때마다 실행되는 것을 알 수 있다.
//컴퍼넌트 디드 마운트와 컴퍼넌트 디드 업데이트와 같은 역할을 한다는 것을 알 수 있다. 
//여러 개를 설치할 수도 있다!!!

  console.log('%cfunc => render'+ (++funcId), funcStyle);
//func => render 1 이 호출되는 것을 콘솔로 확인할 수 있다.
 
  return (
    <div className="container">
      <h2>function style component</h2>
      <p>Number : {number}</p>
      <p>Date : {_date}</p>
      <input type="button" value="random" onClick={
        function() {
          setNumber(Math.random());
        }
       }></input>
      <input type="button" value="date" onClick={
        function() {
          setDate((new Date()).toString());
        }
       }></input>
    </div>
  );
}

어떻게 하면 랜더와 관련된 작업을 하는 FuncComp라는 함수가 실행된 후에 추가적으로 필요한 작업을 처리하게 할 수 있을까?
-> 그것이 바로 리엑트의 유즈 이팩트라는 것.

0개의 댓글