Effect Hook[React]

SnowCat·2023년 1월 17일
0

React - Hooks

목록 보기
3/7
post-thumbnail

※ 공식문서를 읽고 정리한 글입니다.

useEffect

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);
/*
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`;
  }
*/
  • 리액트는 useEffect에 넘긴 함수를 기억하다 DOM 업데이트 시마다 함수를 불러냄
  • useEffect는 컴포넌트 내부에 존재해 effect를 통해 state 변수, prop에 접근할 수 있게 됨
  • 클래스를 사용시 count를 세는 같은 코드가 두개에 메서드에 중복되버리는 것과 다르게 useEffect를 사용하면 코드를 하나로 정리할 수 있음
  • useEffect는 리렌더링 시마다 다른 effect로 교체하여 함수를 전달함
  • 필요한 경우 useEffect를 여러개 사용해 로직을 정리할 수 있음
  • 필요한 경우 useEffect의 두번째 인자로 배열을 넘겨 원하는 값일때만 useEffect가 호출되도록 할 수 있으며, 이 때 배열은 컴포넌트 범위에서 바뀌는 값들과 effect에 의해 사용되는 값들을 모두 포함해야함

clean-up이 필요한 경우

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // effect 이후에 어떻게 정리(clean-up)할 것인지 표시합니다.
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
/*
  componentDidMount() {
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  componentWillUnmount() {
    ChatAPI.unsubscribeFromFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }
  // componentDidUpdate가 없을 시 버그 발생할 위험 있음
  handleStatusChange(status) {
    this.setState({
      isOnline: status.isOnline
    });
  }
*/
  • 클래스에서는 componentWillUnmount에 clean-up 코드를 적어야 했지만, useEffect를 사용하면 return 값에서 clean-up 수행 가능
  • useEffect 사용을 통해 clean-up 코드와 다른 effect 코드를 통합할 수 있음
  • 렌더링 시마다 이전의 렌더링에서 파생된 effect를 정리함으로써 컴포넌트 업데이트시 발생할 수 있는 버그를 사전에 방지해주며 코드의 양을 줄일 수 있음
    주석의 class 코드에서는 componentDidUpdate가 없으면 친구 갱신시 반영되지 않는 문제가 생기며, componentDidUpdate를 작성하더라도 구독과 구독해제를 하는 코드를 작성해야 하기에 코드가 길어짐

출처:
https://ko.reactjs.org/docs/hooks-effect.html

profile
냐아아아아아아아아앙

0개의 댓글