[React] State, Effect Hook 활용하기 (1) (StateAirline Client 과제)

young·2022년 6월 14일
0

5/25~6/22 Section 2 TIL

목록 보기
22/27

onSearch

//1 HTML
<input type="search" onsearch="myFunction()">

  
//2 React
<ChildComponent onSearch={myFunction} />

onsearch event example

React 데이터 흐름

react 컴포넌트는 각자 독립적인 기능을 수행한다.
---> pure function 개념

한 함수는 동일한 input에 동일한 output이 나와야 한다.
---> 동일한 props를 전달하면 동일한 화면이 렌더링 되어야 한다.
그러기 위해 데이터 흐름을 강제해야 한다.
"단방향 데이터 흐름"
props는 상위 컴포넌트에서만 전달되도록 한다.

상태 끌어올리기

lifting state up
부모 컴퍼넌트에서 데이터 상태를 정의, 자식 컴포넌트에서 props로 받는다.
자식 컴포넌트에서 상태 변경 함수를 실행, 부모 컴퍼넌트의 데이터 상태가 변경됨


props는 객체 형태로 전달된다
구조 분해 할당, shorthand 사용


useState

import { useState } from 'react'

const [state, state변경함수] = useState(초기값)

한 컴포넌트의 state는 다른 컴포넌트에 영향을 끼치지 않는다.
각각 관리된다.


useEffect

import { useEffect } from 'react'

컴포넌트 Mount, Update, Unmount

//1 기본형 : Mount, Update, Unmount 모두 렌더링
useEffect(() => {
  //
});


//2 Dependency Array (empty) : Mount시에만 렌더링
useEffect(() => {
  //
}, []);



//3 Dependency Array (props, state) : Mount, Update시 렌더링
useEffect(() => {
  //
}, [deps]);


//Clean Up
useEffect(() => {
  //
  return () => {
  	//Unmount 또는 다음 Mount시에 렌더링됨
  }
}

https://www.youtube.com/watch?v=kyodvzc5GHU&t=71s
위의 영상 보고 만들어본 useEffect


const Timer = (props) => {
  
  useEffect(() => {
    //1초마다 consol.log 실행되는 timer 함수
    const timer = setInterval(() => {
      console.log('타이머 시작')
    }, 1000);

    //Unmount될 시 실행할 clean up 함수
    return () => {
      //타이머 종료
      clearInterval(timer);
      console.log('타이머 종료');
    };
  }, []); //Mount 될 시에만 timer 함수가 동작한다.
  
  ...
  
  return ...
};

profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글