[React] State and Lifecycle

handa·2023년 12월 4일
0
post-thumbnail

1. State

React에서의 state는 React 컴포넌트의 상태를 의미한다.

리액트 Component의 상태 (React 컴포넌트의 데이터)
쉽게 말해 리액트 Component의 변경 가능한 데이터

state는 개발자가 정의한다.
렌더링이나 데이터 흐름에 사용되는 값만 state에 포함시켜야 한다.

state가 변경될 경우 컴포넌트가 재렌더링되기 때문에 렌더링과 데이터 흐름에 관련 없는 값을 포함하면 불필요한 경우에 컴포넌트가 다시 랜더링되어 성능을 저하시킬 수 있기 때문이다.
그렇지 않는 값은 컴포넌트의 인스턴스 필드로 정의하면 된다.

state는 JavaScript 객체이다.

리액트의 state는 따로 복잡한 형태가 있는 것이 아니라 그냥 하나의 자바스크립트 객체이다.

class LikeButton extend React.Component {
	constructor(props) {
    	super(props);
        
        this.state = {
        	liked: false
        };
    }
}

state는 수정이 가능하긴 하지만 그렇게 해서는 안 된다.

React에서의 state는 컴포넌트의 렌더링과 관련이 있기 때문에 개발자가 의도한 대로 작동하지 않을 가능성이 있다.

// state를 직접 수정 (잘못된 사용법)
this.state = {
  name: 'Inje'
};

// setState 함수를 통한 수정 (정상적인 사용법)
this.setState({
  name: 'Inje'
});

2. Lifecycle

Component가 계속 존재하는 것이 아니라, 시간의 흐름에 따라 생성되고 업데이트 되다가 사라진다.

3. 예제

import React from "react";

const styles = {
    wrapper: {
        margin: 8,
        padding: 8,
        display: "flex",
        flexDirection: "row",
        border: "1px solid grey",
        borderRadius: 16,
    },
    messageText: {
        color: "black",
        fontSize: 16,
    },
};

class Notification extends React.Component {
    constructor(props) {
        super(props);

        this.state = {};
    }
  
  	//생명주기 로그출력
    componentDidMount() {
        console.log(`${this.props.id} componentDidMount() called.`);
    }

    componentDidUpdate() {
        console.log(`${this.props.id} componentDidUpdate() called.`);
    }

    componentWillUnmount() {
        console.log(`${this.props.id} componentWillUnmount() called.`);
    }

    render() {
        return (
            <div style={styles.wrapper}>
                <span style={styles.messageText}>{this.props.message}</span>
            </div>
        );
    }
}

export default Notification;
import React from "react";
import Notification from "./Notification";

const reservedNotifications = [
    {
        id: 1,
        message: "안녕하세요, 오늘 일정을 알려드립니다.",
    },
    {
        id: 2,
        message: "점심식사 시간입니다.",
    },
    {
        id: 3,
        message: "이제 곧 미팅이 시작됩니다.",
    },
];

var timer;

class NotificationList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            notifications: [],
        };
    }

    componentDidMount() {
        const { notifications } = this.state;
        timer = setInterval(() => {
            if (notifications.length < reservedNotifications.length) {
                const index = notifications.length;
                notifications.push(reservedNotifications[index]);
                this.setState({
                    notifications: notifications,
                });
            } else {
                this.setState({
                    notifications: [],
                });
                clearInterval(timer);
            }
        }, 1000);
    }

    render() {
        return (
            <div>
                {this.state.notifications.map((notification) => {
                    return (
                        <Notification
                            key={notification.id}
                            id={notification.id}
                            message = {notification.message} 
                        />
                    );
                })}
            </div>
        );
    }
}

export default NotificationList;
profile
진짜 해보자

0개의 댓글