[React] LifeCycle과 useEffect

뽕칠이·2024년 7월 1일
0
post-thumbnail

일반적인 함수를 통해 UseEffect 기능을 구현할 수 없는 이유

import { useState } from 'react'
import Viewer from './components/Viewer';
import Controller from './components/Controller';

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

  const onClickBtn = (value) => {
    setCount(count + value)
    console.log(count)
  }

  return (
    <div className='App'>
      <h1>Simple Counter</h1>
      
      <section>
        <Viewer count={count}/>
      </section>

      <section>
        <Controller onClickBtn={onClickBtn}/>
      </section>
    </div>
  )
}

export default App;

setCount는 비동기적으로 동작하므로 setCountpending 상태가 되면 console.log를 실행한 뒤에 fulfilled 상태가 된 setCount의 결과를 반환한다.


React의 LifeCycle

컴포넌트의 LifeCycle

Every React component goes through the same lifecycle:

  • A component mounts when it’s added to the screen.
  • A component updates when it receives new props or state, usually in response to an interaction.
  • A component unmounts when it’s removed from the screen.

모든 리액트 컴포넌트는 같은 생명주기를 가진다.

  • 컴포넌트는 화면에 추가될 때 마운트된다.
  • 컴포넌트는 새로운 props나 state를 받을 때 업데이트된다. 보통 상호작용에 대한 응답으로 발생한다.
  • 컴포넌트는 화면으로부터 제거될 때 언마운트된다.

Effect란

Before getting to Effects, you need to be familiar with two types of logic inside React components:

  • Rendering code (introduced in Describing the UI) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. Rendering code must be pure. Like a math formula, it should only calculate the result, but not do anything else.
  • Event handlers(introduced in Adding Interactivity) are nested functions inside your components that do things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain “side effects” (they change the program’s state) caused by a specific user action (for example, a button click or typing).

Effect에 가기 전에, 리액트 컴포넌트의 두 가지 내부 논리에 익숙해져야 한다.

  • 렌더링 코드는 컴포넌트의 최상위 레벨에 있다. 여기서 props와 state를 가져와 변환하고, 화면에 표시할 JSX를 반환한다. 렌더링 코드는 반드시 순수해야 한다. 수학 공식처럼, 결과를 계산할 뿐 다른 작업은 하지 않는다.
  • 이벤트 핸들러는 컴포넌트 내부에 있는 함수로 계산만 하는 것이 아니라 별도의 작업도 수행한다. 이벤트 핸들러에서는 입력 필드를 업데이트하거나, HTTP POST 요청을 제출하여 제품을 구매하거나, 사용자를 다른 화면으로 이동할 수 있다. 이벤트 핸들러에 특정 사용자 작업으로 인해 발생하는 "사이드 이펙트"가 포함되어 있다.

Effects let you specify side effects that are caused by rendering itself, rather than by a particular event. Sending a message in the chat is an event because it is directly caused by the user clicking a specific button. However, setting up a server connection is an Effect because it should happen no matter which interaction caused the component to appear. Effects run at the end of a commit after the screen updates. This is a good time to synchronize the React components with some external system (like network or a third-party library).

Effect는 특정 이벤트가 아닌 랜더링 자체로 발생하는 사이드 이펙트를 명시할 수 있다. 채팅에서 메시지를 보내는 것은 사용자가 특정 버튼을 클릭함으로서 직접적으로 발생하기 때문에 이벤트이다. 하지만, 서버 연결을 설정하는 것은 컴포넌트를 나타내기 위해 발생하는 상호작용에 관계없이 일어나야 하기 때문에 Effect다. Effect는 화면 업데이트 후에 커밋이 끝날 때 실행된다. 리액트 컴포넌트를 일부 외부 시스템(네트워크 또는 서드파티 라이브러리)과 동기화하기 좋은 시간이다.


사이드 이펙트란

컴포넌트의 동작에 따라 파생되는 효과를 뜻한다.

동작사이드 이펙트
컴포넌트 내부의 값 변경콘솔에 변경된 값 출력
컴포넌트 마운트콘솔에 "mount" 출력
컴포넌트 업데이트콘솔에 "update" 출력
컴포넌트 언마운트콘솔에 "unmount" 출력

Effect 작성 방법

  1. Effect를 선언한다. Effect는 모든 렌더링 후에 실행된다.
import { useEffect } from "react";

컴포넌트의 최상위 레벨에서 호출하고 Effect 내부에 코드를 추가한다.

const MyComponent = () => {
	useEffect(() =>{
    	//요기의 코드는 매 렌더링 후 실행
    })
  	return <div></div>
}

컴포넌트가 렌더링될 때마다 react는 화면을 업데이트하고 useEffect는 내부의 코드를 실행한다. useEffect는 해당 렌더링이 화면에 반영될 때까지 코드 일부의 실행을 지연한다.

  1. Effect의 의존성을 명시한다. 대부분의 Effect는 렌더링 할 때마다가 아니라 필요할 때만 다시 실행해야 한다.
    -> 예시로 대화방 연결 및 해제는 컴포넌트가 나타났다가 사라지거나 대화방이 변경될 때만 발생해야 한다.

useEffect호출의 두 번째 인자로 의존성 배열을 지정하여 리액트가 불필요하게 Effect를 다시 실행하지 않도록 지정할 수 있다.

const MyComponent = () => {
	useEffect(() =>{
    	//요기의 코드는 매 렌더링 후 실행
    }, [])
  	return <div></div>
}
  1. 필요한 경우 클린업을 추가한다. 일부 Effect는 수행중이던 작업을 중지, 취소 또는 정리하는 방법을 명시해야 한다.

개인적인 결론

useEffect는 의존성 배열에 존재하는 변수가 변경될 때 동작하는 조건문이다.

0개의 댓글