[React] useEffect 실행 순서

장동균·2023년 11월 25일

React에서 useEffect 구문은 즉시 실행되지 않고 스택에 들어간다.
덕분에 나중에 들어온 useEffect 구문이 먼저 실행된다. 즉 자식 컴포넌트의 useEffect 구문이 부모 컴포넌트의 useEffect 구문보다 먼저 실행된다. (useEffect의 인자가 함수인 이유 또한 이와 관련되어 있다.)

const Parent = () => {
  useEffect(() => {
    console.log('I am the parent component')
  }, []);
  return <ChildComponent />;
}

const Child = () => {
  useEffect(() => {
    console.log('I am the child component')
  }, []);  
}

// 출력 결과
// I am the child component
// I am the parent component

그렇다면 부모의 useEffect 구문을 먼저 실행시킬 수 있는 방법은 없을까?
자식의 useEffect가 먼저 실행된다는 사실을 이용하면 이 또한 가능하다. 부모 컴포넌트에서 실행시키고자 하는 useEffect 구문의 함수를 첫번째 자식의 useEffect로 실행시키는 방식이다.

const Parent = () => {
  useEffect(() => {
    console.log('I am parent component')
  }, [)
      
  const fastestEffect = () => console.log('I am fastest effect')
  
  return (
    <>
      <Effect effect={fastestEffect} />
      <Child />
    </>
  )
}

const Effect = ({ effect }) => {
  useEffect(effect, [effect]);
}; 

const Child = () => {
  useEffect(() => {
    console.log('I am the child component')
  }, []);  
}

// 출력 결과
// I am fastest effect
// I am the child component
// I am the parent component

참고문헌

https://gist.github.com/nikparo/33544fe0228dd5aa6f0de8d03e96c378
https://betterprogramming.pub/tips-for-using-reacts-useeffect-effectively-dfe6ae951421

profile
프론트 개발자가 되고 싶어요

1개의 댓글

comment-user-thumbnail
2023년 11월 25일

롤 클라이언트 실행 순서
1. 롤을 실행한다.

답글 달기