React Hook - useState

BANG·2025년 8월 29일

컴포넌트의 상태(state) 관리와 리렌더링 방식 차이

함수형 컴포넌트

  • 변수 초기화: 함수 내부 지역 변수는 초기화됨
  • 상태 변경시: 컴포넌트 함수 전체가 다시 실행됨
  • 상태 유지: useState, useRef 등 Hook으로 유지
  • 부수 효과: useEffect 사용

클래스형 컴포넌트

  • 변수 초기화: 필드 초기화되지 않음
  • 상태 변경시: render() 메서드만 다시 실행
  • 상태 유지: this.state, this에 직접 저장
  • 부수 효과: componentDidMount, componentDidUpdate 등 라이프사이클 메서드 사용

import { useState } from 'react';

const heavyWork = () => {
  console.log("무거운 작업");
  return ['강아지', '고양이'];
}

const App = () => {
  const [value, setValue] = useState(() => {  // 무거운 작업은 콜백형태로!
    return heavyWork();
  });
  const [inputVal, setInputVal] = useState("");

  const handleInputChange = (event) => {
    setInputVal(event.target.value);
  }

  const handleUpload = () => {
    setValue((preValue) => {
      console.log("preValue: ", preValue);
      return [inputVal, ...preValue];
    })
  }

  return (
    <div>
      <input type='text' value={inputVal} onChange={handleInputChange}></input>
      <button onClick={handleUpload}>upload</button>
      {value.map((ele, idx) => { // .map()에서는 (요소, 인덱스) 순서로 고정
        return <li key={idx}>{ele}</li>
      })}
    </div>
  )
};

export default App;
profile
Record Everything!!

0개의 댓글