React

useEffect를 제대로 사용하는 방법 (feat. dan abramov's 포스팅)

westone034626 2022. 7. 14. 19:47

쭉 읽어보니 평소에 useEffect를 사용할 때 놓쳤던 부분들을 많이 발견할 수 있었습니다.

친절하게도 마지막에 다시 한 번 wrap 해주는 부분이 있어서 원문으로 가져왔습니다. 아래에 원문을 의역해서 다시 정리해보았습니다.

 

원문
  • Unlike events, effects are caused by rendering itself rather than a particular interaction.
  • Effects let you synchronize a component with some external system (third-party API, network, etc).
  • By default, effects run after every render (including the initial one).
  • React will skip the effect if all of its dependencies have the same values as during the last render.
  • You can’t “choose” your dependencies. They are determined by the code inside the effect.
  • An empty dependency array ([]) corresponds to the component “mounting”, i.e. being added to the screen.
  • When Strict Mode is on, React mounts components twice (in development only!) to stress-test your effects.
  • If your effect breaks because of remounting, you need to implement a cleanup function.
  • React will call your cleanup function before the effect runs next time, and during the unmount.

 

의역
  • 유저 interaction(click) 같은 event와 달리 effect(useEffect 내부의 함수를 지칭)는 컴포넌트의 랜더링에 의해 발생합니다.
  • effect는 external system과 컴포넌트를 동기화 할 때 사용합니다.(external system: web API, network 등 의미)
  • 기본적으로 effect는 매랜더링마다 호출됩니다.
  • 기존 랜더링 됐을 때의 dependency array 값과 새롭게 랜더링 됐을 때의 dependency array 값이 동일하다면 effect는 skip 됩니다.
  • dependency array는 effect 내부에서 사용되는 코드에 따라 결정되는 것이지 우리가 임의로 선택하는 개념이 아닙니다.
  • dependency array에 빈배열([])을 입력하면 컴포넌트가 화면에 추가되는 시점에만 effect 함수가 호출됩니다.
  • 개발 모드에서 의도적으로 리액트 컴포넌트를 두 번씩 화면에 mount 시킵니다.(effect가 잘 작성됐는지 테스트하기 위함)
  • 만약 컴포넌트가 remount되는 시점에 effect가 문제를 일으킨다면 cleanup function을 작성해야합니다.(ex: clearTimeout)
  • 리액트는 다음 effect 함수를 호출하기 전에 clean-up function을 호출할 것입니다.(or unmount될 때)

 

다시 한 번 더...

 

  1. effect는 렌더링 자체와 관련된 일을 하기 위함이지 event와 관련된 일을 하기 위함이 아니다.
    1. 예시1: 채팅 메시지를 누르는 버튼을 클릭하는 것은 event가 처리할 일(effect no)
    2. 예시2: 컴포넌트 렌더링 이후 채팅 서버와 연결을 하는 작업은 effect가 하는 일(event no)
    3. 부연 설명: Effects run at the end of the rendering process 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). 

 

 

참고: https://beta-reactjs-org-git-effects-fbopensource.vercel.app/learn/synchronizing-with-effects

 

Synchronizing with Effects

A JavaScript library for building user interfaces

beta.reactjs.org