React useEffect Hook을 사용하는 방법

8568 단어 reacttutorial
Hook은 v16.8(2018)부터 React에서 사용할 수 있으며 함수 구성 요소가 상태 및 부작용을 관리할 수 있도록 합니다. 기존 코드와 나란히 작동합니다. 다른 많은 훌륭한 기능이 있습니다. Intro to React Hooks 블로그 게시물을 확인하세요.

React는 useState 및 useEffect와 같은 몇 가지 내장 Hook을 제공합니다. 이 블로그 게시물은 useEffect 후크에 관한 것입니다. React useState 후크에 대한 자세한 내용은 이 블로그 게시물How to use the useState hook을 확인하세요.

💰: Start your cloud journey with $100 in free credits with DigitalOcean!

사용 효과

The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. They can also be just called effects.

The useEffect Hook can be understood as componentDidMount, componentDidUpdate, and componentWillUnmount combined in the React class lifecycle methods.

There are two different types of side effects in React components:

  • those that don’t require cleanup, and
  • those that do.

정리 없는 효과

Some examples of effects that don’t require a cleanup are network requests, manual DOM mutations, and logging. We can run them and immediately forget about them.

Let's have a look on how class components and function components can handle these type of side effects.

The following example is based on the counter example from the useState hook 블로그 게시물. React가 DOM을 업데이트한 후 문서 제목을 업데이트하고 싶다고 가정해 봅시다.

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>
    );
  }
}


React 클래스에서 부작용은 수명 주기 상태에 있습니다. 이 경우에는 componentDidMount 및 componentDidUpdate에서 발생합니다. 위의 코드 예제에서 볼 수 있듯이 코드 중복이 있습니다. 대부분의 경우 기본적으로 모든 렌더링 후에 방금 마운트했거나 업데이트된 구성 요소를 업데이트하려고 합니다.

React Hooks 사용과 동일한 사용 사례:

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}


useEffect Hook을 사용하면 컴포넌트가 렌더링 후에 무언가를 해야 한다고 React에 알릴 수 있습니다. React는 DOM 업데이트를 수행한 후 효과를 호출합니다.

useEffect Hook은 추가 API 없이 효과에서 바로 상태(count 변수)에 액세스하기 위해 구성 요소 내부에 배치되며 이미 범위에 있습니다.

Hooks는 JavaScript 클로저를 수용하고 JavaScript가 이미 솔루션을 제공하는 React 관련 API를 도입하지 않습니다.

useEffect 후크는 모든 렌더링에서 실행됩니다. React 클래스에서 왔다면 마운트 또는 마운트 해제처럼 생각하지 말고 렌더링 후와 같이 useEffect를 생각하십시오.

useEffect Hook을 자세히 살펴보면 여기에 전달된 함수가 렌더링할 때마다 변경되는 것을 볼 수 있습니다. 이것은 의도적이며 카운트가 부실해지는 것에 대해 걱정할 필요가 없습니다. 다시 렌더링할 때마다 이전 효과를 대체하여 다른 효과를 예약합니다.

useEffect로 예약된 효과는 브라우저가 화면을 업데이트하는 것을 차단하지 않으며 componentDidMount 또는 componentDidUpdate는 차단합니다.

정리 효과

The other type of effects, are effects which require a cleanup. This could be a subscription to some external data source. If we don't clean up after subscribing we would introduce a memory leak in our application.

The React docs also have a great example for this, which I am going to utilize below. Let’s say we have a ChatAPI module that lets us subscribe to a friend’s online status, and we compare using Classes and using Hooks.

In a React Class component , you would typically set up a subscription in componentDidMount , and clean it up in componentWillUnmount .

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';
  }
}

The lifecycle methods componentDidMount and componentWillUnmount need to mirror each other. Lifecycle methods force us to split this logic even though conceptually code in both of them is related to the same effect.

In a React Function Component with the useEffect Hook the code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together. If your effect returns a function, React will run it when it is time to clean up.

With the useEffect Hook it could be written like this:

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';
}

Every effect may return a function that cleans up after it. This lets us keep the logic for adding and removing subscriptions close to each other, and they're just part of the same effect.

React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.

TL;DR

  • The Effect Hook lets you perform side effects in function components.
  • There are two different types of useEffect hooks, with cleanup and without.
Thanks for reading and if you have any questions , use the comment function or send me a message . If you want to know more about React , 이것들을 보세요 React Tutorials .

참조(그리고 큰 감사):

React Hooks , Using the Effect Hook

좋은 웹페이지 즐겨찾기