반응형
Jake Seo
제이크서 위키 블로그
Jake Seo
전체 방문자
오늘
어제
  • 분류 전체보기 (715)
    • 일상, 일기 (0)
    • 백준 문제풀이 (1)
    • 릿코드 문제풀이 (2)
    • 알고리즘 이론 (10)
      • 기본 이론 (2)
      • 배열과 문자열 (8)
    • 데이터베이스 (15)
      • Planet Scale (1)
      • MSSQL (9)
      • 디비 기본 개념 (1)
      • SQLite 직접 만들어보기 (4)
    • 보안 (7)
    • 설계 (1)
    • 네트워크 (17)
      • HTTP (9)
      • OSI Layers (5)
    • 회고 (31)
      • 연간 회고 (2)
      • 주간 회고 (29)
    • 인프라 (52)
      • 도커 (12)
      • AWS (9)
      • 용어 (21)
      • 웹 성능 (1)
      • 대규모 서비스를 지탱하는 기술 (9)
    • 깃 (7)
    • 빌드 도구 (7)
      • 메이븐 (6)
      • 그레이들 (0)
    • Java (135)
      • 이펙티브 자바 (73)
      • 자바 API (4)
      • 자바 잡지식 (30)
      • 자바 디자인 패턴 (21)
      • 톰캣 (Tomcat) (7)
    • 프레임워크 (64)
      • next.js (14)
      • 스프링 프레임워크 (28)
      • 토비의 스프링 (6)
      • 스프링 부트 (3)
      • JPA (Java Persistence API) (5)
      • Nest.js (8)
    • 프론트엔드 (48)
      • 다크모드 (1)
      • 노드 패키지 관리 매니저 (3)
      • CSS (19)
      • Web API (11)
      • tailwind-css (1)
      • React (5)
      • React 새 공식문서 요약 (1)
      • HTML (Markup Language) (5)
    • 자바스크립트 (108)
      • 모던 자바스크립트 (31)
      • 개념 (31)
      • 정규표현식 (5)
      • 코드 스니펫 (1)
      • 라이브러리 (6)
      • 인터뷰 (24)
      • 웹개발자를 위한 자바스크립트의 모든 것 (6)
      • 팁 (2)
    • Typescript (49)
    • 리눅스와 유닉스 (10)
    • Computer Science (1)
      • Compiler (1)
    • IDE (3)
      • VSCODE (1)
      • IntelliJ (2)
    • 세미나 & 컨퍼런스 (1)
    • 용어 (개발용어) (16)
      • 함수형 프로그래밍 용어들 (1)
    • ORM (2)
      • Prisma (2)
    • NODEJS (2)
    • cypress (1)
    • 리액트 네이티브 (React Native) (31)
    • 러스트 (Rust) (15)
    • 코틀린 (Kotlin) (4)
      • 자바에서 코틀린으로 (4)
    • 정규표현식 (3)
    • 구글 애널리틱스 (GA) (1)
    • SEO (2)
    • UML (2)
    • 맛탐험 (2)
    • 리팩토링 (1)
    • 서평 (2)
    • 소프트웨어 공학 (18)
      • 테스팅 (16)
      • 개발 프로세스 (1)
    • 교육학 (1)
    • 삶의 지혜, 통찰 (1)
    • Chat GPT (2)
    • 쉘스크립트 (1)
    • 컴파일 (2)
    • Dart (12)
    • 코드팩토리의 플러터 프로그래밍 (4)
    • 플러터 (17)
    • 안드로이드 스튜디오 (1)
    • 윈도우즈 (1)
    • 잡다한 백엔드 지식 (1)
    • 디자인 패턴 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 이펙티브자바
  • 외래키 제약조건
  • 자바 디자인패턴
  • 추상 팩터리 패턴
  • 이펙티브 자바
  • next js app
  • 스프링 검증
  • prerendering
  • Next.js
  • 슬로우 쿼리
  • 자료구조
  • 싱글턴
  • rust
  • item8
  • 싱글톤 패턴
  • 빈 검증
  • 메이븐 페이즈
  • MSSQL
  • 참조 해제
  • 서버리스 컴퓨팅
  • 작업기억공간
  • 프로그래머의 뇌
  • 자바
  • 자바 검증
  • serverless computing
  • 알고리즘
  • 플라이웨이트패턴
  • 팩터리 메서드 패턴
  • 자바스크립트
  • 메이븐 골
  • 자바스크립트 인터뷰
  • 도커공식문서
  • Pre-rendering
  • 자바스크립트 면접
  • pnpm
  • 토비의 스프링
  • 객체복사
  • try-with-resources
  • Javadoc 자바독 자바주석 주석 Comment
  • Java
  • NEXT JS
  • item7
  • 싱글톤
  • bean Validation
  • item9
  • 러스트
  • 느린 쿼리
  • 이펙티브 자바 item9
  • 디자인패턴
  • 메이븐 라이프사이클

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Jake Seo

제이크서 위키 블로그

프론트엔드/React

React Effect Hook 이란?

2022. 10. 19. 20:54

Effect Hook 이란?

  • 함수형 컴포넌트에서 사이드 이펙트를 만들 수 있도록 해주는 리액트 훅이다.
  • useEffect() 와 같은 함수를 이용해 만들 수 있다.
  • 기본적으로 DOM 리랜더링이 일어날 때마다 사이드 이펙트가 작동하며 컴포넌트가 화면에서 사라지면 return 에 작성해둔 clean up 함수가 실행된다.
  • 두번째 파라미터에 배열로 state 값의 인자를 주면, 해당 값이 바뀌어 리랜더링이 될 때만 사이드 이펙트가 동작한다.
  • 기존 클래스형 컴포넌트 라이프 사이클에서 componentDidMount 가 가지던 효과와 비슷하다.

Effect Hook 과거와 현재 비교하기

카운트가 증가할 때마다, useEffect() 의 사이드이펙트에 의해 title 도 함께 수정되는 예제를 작성해본 것이다.

예전의 클래스 컴포넌트를 사용한다면?

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }
  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

함수형 컴포넌트와 Effect Hook 을 사용한다면?

import React, { useState, useEffect } from "react";
function Example() {
  const [count, setCount] = useState(0);
  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

간접적으로 useEffect 는 componentDidMount 와 componentDidUpdate 두개를 합친 역할을 한다는 것을 알 수 있다.

useEffect 는 componentDidMount 나 componentDidUpdate 와 같이 스크린 업데이트를 블록하지 않으므로, 사용성이 더 좋게 느껴질 수 있다. 왜냐하면 대부분의 effect 는 동기적으로 수행될 필요가 없기 때문이다.

Effect Hook with Cleanup

때때로는 컴포넌트가 마운트될 때, 사이드이펙트가 등록되고 컴포넌트가 언마운트될 때 사이드이펙트가 해제되어야 하는 경우도 있다.

아래는 ChatAPI 를 구독하며 실시간으로 친구의 상태를 관찰하는 컴포넌트의 예제이다. 이 컴포넌트가 unmount 되는 경우에는 구독이 해제되어야 한다.

예전의 클래스 컴포넌트를 사용한다면?

class FriendStatus extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isOnline: null };
    this.handleStatusChange = this.handleStatusChange.bind(this);
  }
  componentDidMount() {
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  handleStatusChange(status) {
    this.setState({
      isOnline: status.isOnline,
    });
  }
  render() {
    if (this.state.isOnline === null) {
      return "Loading...";
    }
    return this.state.isOnline ? "Online" : "Offline";
  }
}

componentDidMount() 와 componentWillUnmount() 라이프사이클을 이용하여 이벤트를 구독하고 구독해지하도록 구성했다.

함수형 컴포넌트의 Effect Hook 을 사용한다면?

import React, { useState, useEffect } from "react";
function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });
  if (isOnline === null) {
    return "Loading...";
  }
  return isOnline ? "Online" : "Offline";
}

useEffect() 콜백 함수 내부에서 cleanup() 콜백 함수를 반환함으로써, 클래스형 컴포넌트의 라이프사이클 중 하나인 componentWillUnmount() 와 같은 역할을 하도록 구성했다.

해당 함수형 컴포넌트가 언마운트 되는 시점에 구독이 해지될 것이다. 또한 리액트는 다음 동작을 수행 전에도 cleanup() 콜백 함수를 실행할 것이다.

Effect Hook 장점

관심사에 대한 분리 가능

class FriendStatusWithCounter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0, isOnline: null };
    this.handleStatusChange = this.handleStatusChange.bind(this);
  }
  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  handleStatusChange(status) {
    this.setState({
      isOnline: status.isOnline
    });
  }

클래스형 컴포넌트의 예제는 이벤트 기반이라 코드가 관심사에 따라 나누어졌다고 보기보다는 타이밍에 따라 나누어졌다.

function FriendStatusWithCounter(props) {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  const [isOnline, setIsOnline] = useState(null);
  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });
}

함수형 컴포넌트의 useEffect() 는 여러 개를 관심사에 따라 나눠서 작성할 수 있다.

변화가 있을 때만 사이드 이펙트가 작동하게 만들기 쉽다.

componentDidUpdate(prevProps, prevState) {
  if (prevState.count !== this.state.count) {
    document.title = `You clicked ${this.state.count} times`;
  }
}

클래스형 컴포넌트에서 카운트가 이전 값에서 바뀌었는지 확인하려면 props 를 전달해주어야 한다.

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

함수형 컴포넌트 useEffect() 에서는 해당 이펙트를 실행시키기 위해 변화를 관찰할 값을 넣어 dependencies 배열만 조정해주면 된다.

useEffect(() => {
  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }
  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
  return () => {
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
  };
}, [props.friend.id]); // Only re-subscribe if props.friend.id changes

위도 같은 예제이다.

실수하기 쉬운 부분

const App = () => {
  const [number, setNumber] = useState(0);
  useEffect(() => {
    console.log("component did mount with useEffect!");
    return () => {
      console.log("component will unmount");
    };
  }, [number]);
  return (
    <div>
      <h2>number is {number}</h2>
      <button
        onClick={() => {
          setNumber(number + 1);
        }}
      >
        Increment
      </button>
    </div>
  );
};

위와 같이 코드를 작성하면, 매번 number 가 바뀔 때마다 "component will unmount" 라는 콘솔 로그를 함께 보게될 것이다. 그 이유는 dependencies 때문에 number 값을 관찰하기 때문이다. 마운트, 언마운트 시 한 번만 수행할 작업은 dependencies 를 걸지 않아야 정상동작할 것이다.

레퍼런스

  • 공식문서 Using the Effect Hook
반응형
저작자표시 비영리 (새창열림)

'프론트엔드 > React' 카테고리의 다른 글

리액트 컴포넌트 밖 변수 선언의 의미 (Feat. 리액트에서 절대 하면 안되는 것 1가지)  (0) 2022.10.14
React 컴포넌트 어떻게 나누고 재사용할 것인가?  (0) 2022.07.24
React Hook Form 이 해결하는 문제들과 사용법  (0) 2022.07.02
React Hook Form 소개  (0) 2022.07.02
    '프론트엔드/React' 카테고리의 다른 글
    • 리액트 컴포넌트 밖 변수 선언의 의미 (Feat. 리액트에서 절대 하면 안되는 것 1가지)
    • React 컴포넌트 어떻게 나누고 재사용할 것인가?
    • React Hook Form 이 해결하는 문제들과 사용법
    • React Hook Form 소개
    Jake Seo
    Jake Seo
    ✔ 잘 보셨다면 광고 한번 클릭해주시면 큰 힘이 됩니다. ✔ 댓글로 틀린 부분을 지적해주시면 기분 나빠하지 않고 수정합니다. ✔ 많은 퇴고를 거친 글이 좋은 글이 된다고 생각합니다. ✔ 간결하고 명료하게 사람들을 이해 시키는 것을 목표로 합니다.

    티스토리툴바