본문 바로가기

Programming/React

[React] Hooks에서 state 변경 시 re-render 방법

문제 출발점 :

react 부모 component 밑에 child component간 데이터를 주고 받은 후 re-render 하려면 어떻게 해야하나?

 

기본 이해 : Class 기반 React JS Life Cycle

constructor 

componentWillMount

componentDidMount 

componentWillUnmount

Import React from "react";

class example extends React.Component{
       constructor(){
            super();
            console.log("constructor");
       }

       componentWillMount(){
            console.log("componentWillMount");
       }

       componentDidMount(){
            console.log("componentDidMount");
       }

      render(){
          console.log("render");
          return(
                  <div> Helllo </div>     
      }

}

 

 

해결 방법 : Hooks에서는 useEffect를 통해 Lifecycle(render)을 관리

 

 - useEffect는 클래스 기반 Lifecycle 메소드에서

    componentDidMount / componentDidUpdate / componentWillUnmont 의 역할을 함

 

useEffect(<function>, <Array>);
<function> : 컴포넌트가 render 또는 re-render 되었을 때 실행하고 싶은 함수
<Array> : 어떤 state가 변화되었을 때 컴포넌트를 re-render할지 를 나타내는 인자

useEffect( () => {console.log("component did mount with useEffect!"); , []);

Array에 " [ ] " 으로 주게 되면 이 의미는 "state가 변화되더라도 컴포넌트를 re-render하지 않겠다" 라는 의미

 

예제

import React, { useState, useEffect } from "react";

const exampleHooks = () => {
  const [numberIncrease, setNumber] = useState(0);
  
  useEffect(() => {
    console.log("component did mount with useEffect!");
  }, [numberIncrease]);
  
  return (
    <div>
      <h2>number is {numberIncrease}</h2>
      <button
        onClick={() => {
          setNumber(numberIncrease + 1);
        }}
      >
        +1
      </button>
    </div>
  );
};

 

 

결론 :

react hooks에서 component 간 state 를 변경해서

re-render 해주고 싶은 경우 "useEffect"를 활용하자

반응형