Notice
Recent Posts
Recent Comments
Link
«   2025/09   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발자의 자기계발 블로그( ੭ ・ᴗ・ )੭

[React] 상태(State)와 생명주기(Lifecycle) 본문

JS

[React] 상태(State)와 생명주기(Lifecycle)

쪼사원 2024. 6. 19. 16:12

목차

    ✅ State (상태)

    상태는 리액트 컴포넌트에서 관리되는 동적인 데이터

    상태는 컴포넌트가 동작하고 변하는 방식을 정의하며, 상태가 변경되면 컴포넌트는 다시 렌더링된다!!

     

    ✔ 상태의 정의

    상태는 컴포넌트 내부에서 정의되며, 클래스형 컴포넌트와 함수형 컴포넌트에서 다르게 처리된다.

     

    1. 클래스형 컴포넌트에서 상태

    • 상태는 constructor 메서드에서 초기화되며, 객체 형태로 저장된다.
    • 상태를 변경하려면 this.setState 메서드를 사용해야함.
    class Counter extends React.Component {
        constructor(props){
            super(props);
            this.state={
                count : 0
            };
        }
    
        increment = () => {
            this.setState({count: this.state.count + 1});
        }
    
        render() {
            return (
                <div>
                    <p>Count: {this.state.count}</p>
                    <button onClick={this.increment}>Increment</button>
                </div>
            );
        }
    }

     

     

    2. 함수형 컴포넌트에서 상태

    • 함수형 컴포넌트에서는 useState 훅을 사용하여 상태를 정의하고 관리한다
    • 상태와 함께 상태를 업데이트하는 함수를 반환한다
    import React, {useState} from "react";
    
    function Counter() {
        const [count, setCount] = userState(0);
    
        return (
            <div>
                <p>Count: {count}</p>
                <button onClick={() => setCount(count + 1)}>Increment</button>
            </div>
        );
    }

     


    ❓ About constuctor 메서드

    constructor 메서드는 클래스형 컴포넌트에서 초기 상태(state)와 props를 설정하고,

    이벤트 핸들러를 바인딩하는 데 사용되는 특별한 메서드이다.

    ES6 클래스 문법의 일부로, 리액트 컴포넌트에서는 컴포넌트 인스턴스가 생성될 때 호출됨!

     

    ✔ 주요 기능

     

    1. 초기 상태 설정

    •  constructor  메서드 내부에서 this.state를 설정하여 초기 상태를 정의할 수 있다.
    class MyComponent extends React.Component {
        constructor(props) {
            super(props); // 부모 클래스의 생성자를 호출
            this.state = {
            	count: 0 // 초기상태 설정
        };
    }
    render() {
        	return <div>{this.state.count}</div>;
        }
    }

     

    2. props 초기화

    • constructor는 props를 인수로 받아 부모 컴포넌트로부터 전달된 프롭스를 초기화 한다.
    • super(props)를 호출하여 부모 클래스의 생성자에 props를 전달해야 한다.

    3. 이벤트 핸들러 바인딩

    • constructor 메서드 내부에서 this를 바인딩하여 이벤트 핸들러 메서드를 인스턴스와 연결할 수 있다.

    ✔ 주의사항

    • super(props) 호출 : constructor 메서드 내에서 this를 사용하기 전에 반드시 super(props)를 호출해야함!!
      이는 React.Component의 생성자를 호출하여 props를 초기화하는 역할을 함
    • setState 호출 불가 : constructor 내에서는 setState를 호출할 수 없음.
      초기 상태는 직접 this.state에 할당해야 된다.

     

    함수형 컴포넌트에는 constructor 메서드가 없음!!

    상태와 이벤트 핸들러는 useState와 useEffect 훅을 사용하여 설정한다.

    import React, {useState} from "react";
    
    function MyComponent(props){
        const [count, setCount] = useState(0);
    
        const handleClick = () => {
            setCount(count + 1);
        };
    
        return (
            <div>
                <button onClick= {handleClick}>Increment</button>
                <div>{count}</div>
            </div>
        );
    }

     

     

    ✅ 생명주기 (Lifecycle)

    생명주기란 리액트 컴포넌트가 생성되고, 업데이트 되고, 제거될 때까지의 일련의 과정을 말한다.

    생명주기 메서드는 클래스형 컴포넌트에서만 사용할 수 있음!!

    하지만 훅을 사용하면 함수형 컴포넌트에서도 유사한 기능을 구현할 수 있음!!

     

    ✔ 주요 생명주기 메서드

    1. 마운트(Mount)

    • 컴포넌트가 처음 DOM에 삽입될 때 실행되는 단계
    • 주요 메서드 : 'constructor', 'componentDidMount'
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
        console.log('Constructor');
      }
    
      componentDidMount() {
        console.log('Component did mount');
      }
    
      render() {
        return <div>{this.state.count}</div>;
      }
    }

     

    2. 업데이트 (Update)

    • 컴포넌트의 상태나 프롭스가 변경되어 다시 렌더링 될 때 실행되는 단계
    • 주요 메서드 : 'shouldComponentUpdate', 'componentDidUpdate'
    class MyComponent extends React.Component {
      componentDidUpdate(prevProps, prevState) {
        if (this.state.count !== prevState.count) {
          console.log('Component did update');
        }
      }
    
      render() {
        return <div>{this.state.count}</div>;
      }
    }

     

    3. 언마운트 (Unmount)

    • 컴포넌트가 DOM에서 제거될 때 실행되는 단계
    • 주요 메서드 : 'componentWillUnmount'
    class MyComponent extends React.Component {
      componentWillUnmount() {
        console.log('Component will unmount');
      }
    
      render() {
        return <div>{this.state.count}</div>;
      }
    }

     

     

    ➕ 함수형 컴포넌트에서 생명주기 처리

    함수형 컴포넌트에서는 useEffect 훅을 사용하여 생명주기 메서드와 유사한 기능을 구현할 수 있음

    useEffect 훅은 컴포넌트가 렌더링될 때마다 실행되며, 특정 조건에 따라 실행을 제어할 수 있음

    Hook은 다음 포스팅에서 자세히 다루도록 하겠습니당

    import React, { useState, useEffect } from 'react';
    
    function MyComponent() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        console.log('Component did mount or update');
    
        return () => {
          console.log('Component will unmount');
        };
      }, [count]); // count가 변경될 때마다 실행
    
      return <div>{count}</div>;
    }

     

    'JS' 카테고리의 다른 글

    [React] Hook의 개념, 그리고 주요 Hook (UseState, UseEffect)  (0) 2024.06.24
    [React] Components와 Props  (0) 2024.06.18
    [React] Rendering Elements  (0) 2024.06.17
    [React] JSX  (0) 2024.06.17
    [React] 리액트 시작하기전에 & 소개  (0) 2024.06.14