7주차 위클리 페이퍼

보리·2024년 4월 16일
0

codeit-sprint

목록 보기
20/22

❓리액트에서 배열을 렌더링할 때 key를 써야 하는 이유에 대해 설명해 주세요.

  • Key는 React에서 컴포넌트 리스트를 렌더링할 때 각 항목을 고유하게 식별하는 데 사용된다.
  • 각 요소에 고유한 key 값을 부여함으로써 리액트는 각 요소를 안정적으로 식별할 수 있다.
  • 요소의 추가, 삭제, 변경 등의 변화를 효과적으로 감지할 수 있다.
  • 배열의 고유한 식별자(예: id)를 key 값으로 사용하는 것이 가장 좋다.

key를 사용하지 않으면❓

  • 배열의 변화를 잘 감지하지 못해 전체 배열을 다시 렌더링할 수 있다.
  • 배열의 순서가 변경되면 React는 각 항목을 새로운 위치에 렌더링할 때 이전 위치와의 비교를 통해 업데이트한다. 하지만 key 값이 없는 경우 React는 각 항목을 고유하게 식별할 수 없어서 예기치 않은 결과가 발생할 수 있다.
import React from 'react';

function ExampleComponent() {
  const items = ['A', 'B', 'C'];

  const listItems = items.map((item, index) =>
    <li key={index}>
      {item}
    </li>
  );

  return (
    <ul>
      {listItems}
    </ul>
  );
}

export default ExampleComponent;

❓리액트 생명주기(life cycle)에 대해 설명해 주세요.

React 컴포넌트의 라이프 사이클은 컴포넌트가 생성, 업데이트, 소멸되는 일련의 단계를 말한다. 라이프 사이클 메소드는 이러한 단계에서 실행되는 함수들을 말하며, 클래스형 컴포넌트에서 주로 사용된다.

1. Mounting (생성 단계)

컴포넌트가 처음 렌더링될 때 발생하는 단계

  • constructor(): 컴포넌트가 생성될 때 호출되는 생성자 메소드.
  • static getDerivedStateFromProps(): props를 통해 파생된 상태를 설정할 때 사용되는 메소드.
  • render(): UI를 렌더링하는 메소드.
  • componentDidMount(): 컴포넌트가 실제 DOM에 추가된 후 호출되는 메소드.

2. Updating (업데이트 단계)

컴포넌트가 업데이트될 때 발생하는 단계

  • static getDerivedStateFromProps(): props를 통해 파생된 상태를 업데이트할 때 호출.
  • shouldComponentUpdate(): 컴포넌트가 업데이트 여부를 결정하는 메소드.
  • render(): UI를 업데이트하는 메소드.
  • getSnapshotBeforeUpdate(): 업데이트 전에 이전의 DOM 상태를 캡처하는 메소드.
  • componentDidUpdate(): 컴포넌트가 업데이트를 완료한 후 호출되는 메소드.

3. Unmounting (소멸 단계)

컴포넌트가 DOM에서 제거될 때 발생하는 단계

  • componentWillUnmount(): 컴포넌트가 제거되기 전에 호출되는 메소드.

4. Error Handling (에러 처리 단계)

컴포넌트 렌더링 중 에러가 발생할 때 호출되는 단계

  • static getDerivedStateFromError: 하위 컴포넌트에서 오류가 발생할 때 호출.
  • componentDidCatch: 하위 컴포넌트에서 발생한 오류를 처리하기 위해 호출.
// 실행했을 때의 순서: -1-, -2- ...
// 버튼 클릭 후의 순서: (1), (2) ...
import React, { Component } from 'react';

class LifeCycleExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
    // 컴포넌트가 생성될 때 호출되는 생성자 메서드 -1-
    console.log('Constructor called'); 
  }

  static getDerivedStateFromProps(props, state) {
    // props로부터 state를 도출할 때 호출되는 메서드 -2- (1)
    console.log('getDerivedStateFromProps called'); 
    return null;
  }

  componentDidMount() {
    // 컴포넌트가 마운트된 직후 호출되는 메서드 -4-
    console.log('componentDidMount called'); 
  }

  shouldComponentUpdate(nextProps, nextState) {
    // 컴포넌트 업데이트 여부를 결정할 때 호출되는 메서드  (2)
    console.log('shouldComponentUpdate called'); 
    return true;
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // 실제 DOM에 변화가 반영되기 직전 호출되는 메서드  (4)
    console.log('getSnapshotBeforeUpdate called'); 
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // 컴포넌트 업데이트 직후 호출되는 메서드 -6-  (5)
    console.log('componentDidUpdate called');
  }

  componentWillUnmount() {
    // 컴포넌트가 언마운트되기 직전 호출되는 메서드 -5-
    console.log('componentWillUnmount called'); 
  }

  handleClick = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
  };

  render() {
    // 컴포넌트가 렌더링될 때 호출되는 메서드 -3-  (3)
    console.log('Render called'); 
    return (
      <div>
        <h1>React Lifecycle Example</h1>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

export default LifeCycleExample;

https://ko.legacy.reactjs.org/docs/react-component.html#the-component-lifecycle

📍함수형 컴포넌트와 Hooks

최근에는 함수형 컴포넌트와 Hooks가 많이 사용되고 있다. 함수형 컴포넌트에서는 생명주기 메서드 대신 useEffect Hook을 사용하여 비슷한 작업을 수행할 수 있다.

useEffect는 컴포넌트가 마운트, 업데이트, 언마운트될 때 특정 작업을 수행할 수 있게 해준다.

예) useEffect의 두 번째 인자로 빈 배열을 전달하면 마운트 시에만 실행되는 것과 유사한 효과를 얻을 수 있다. 또한 의존성 배열을 통해 특정 state 변화에 반응하도록 할 수 있다.

이처럼 함수형 컴포넌트와 Hooks를 사용하면 생명주기 메서드를 직접 사용하지 않고도 컴포넌트의 상태 관리와 부수 효과 처리가 가능하다.

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

function LifeCycleHooksExample() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // 컴포넌트가 마운트되거나 업데이트될 때 호출되는 useEffect
    console.log('Component mounted or updated'); 
    
    return () => {
      // 컴포넌트가 언마운트될 때 호출되는 cleanup 함수
      console.log('Component will unmount'); 
    };
  }, []);

  useEffect(() => {
    // count state가 변경될 때 호출되는 useEffect
    console.log('Count state changed');
  }, [count]);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>React Lifecycle Hooks Example</h1>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default LifeCycleHooksExample;
profile
정신차려 이 각박한 세상속에서

0개의 댓글