필자는 스크롤 비율에 따라 애니메이션이 작동하는 웹 페이지를 리액트로 개발하고 있었다.
canvas나 div의 속성을 스크롤 비율에 따라 바꿔주는 기능을 구현 했는데, 애니메이션적인 변화가 필요한 요소들은 useRef를 사용하여 레퍼런스로 등록을 해놨었고, react-router-dom을 사용하여 A page 에서 B page로 옮겨가는 상황이 발생했다고 하자.................
1. App.js
import React, { useState, useEffect, useLayoutEffect } from 'react';
import Section1 from './components/Section1';
import Section2 from './components/Section2';
const App = () => {
const [compo, setCompo] = useState('초기화');
const firstClick = () => {
setCompo(<Section1></Section1>)
}
const secondClick=()=> {
setCompo(<Section2></Section2>)
}
return(
<>
<button onClick={firstClick}> section1 </button>
<button onClick={secondClick}> section2 </button>
{compo}
</>
)
}
export default App;
2. Section1.jsx
import React, { useState, useEffect, useLayoutEffect } from 'react';
const Section1 = () => {
const [title, setTitle] = useState('section1');
console.log('section1 rendered')
useEffect(()=> {
console.log('section1 useEffect start');
return(()=> {
console.log('section1 useEffect return start');
})
}, [])
return(
<>
<div>
{title} 입니다.
</div>
</>
)
}
export default Section1;
3. Section2.jsx
import React, { useEffect, useState } from 'react';
const Section2 = () => {
const [title, setTitle] = useState('section2');
console.log('section2 rendered')
useEffect(()=>{
console.log('section2 useEffect start');
return(()=> {
console.log('section2 useEffect return start')
})
}, []);
return(
<>
{title} 입니다.
</>
)
}
export default Section2;
1. App.js
Section1.jsx, Section2.jsx를 import 하며 버튼 두 개를 렌더링한다.
버튼을 클릭하면 Section1.jsx 또는 Section2.jsx가 렌더링된다.

2. Section1.jsx, Section2.jsx (공통사항)
컴포넌트가 렌더링 되면 콘솔에 section1 (or section2) rendered.가 출력이 된다.
useEffect가 실행되는 시점에서는 section1 (or section2) useEffect start가 콘솔에 출력된다.
컴포넌트가 언마운트 되는 시점에 useEffect가 return을 반환하면서 section1 (or section2 useEffect return start가 콘솔에 찍힌다.

컴포넌트가 렌더링 된 후 useEffect가 실행되는 것을 알 수 있다.

순서를 나열해보면,
Section2 컴포넌트가 렌더링 된다.
Section1의 useEffect가 return을 실행한다.
Section2의 useEffect가 실행된다.
다음 컴포넌트가 렌더링되고, 이전 컴포넌트의 useEffect가 마무리 된 후 다음 컴포넌트의 useEffect가 실행된다.
컴포넌트 렌더링
useEffect 실행
(A page 👉 B page)
B 컴포넌트 렌더링
A useEffect return 실행
B useEffect 실행
유능합니다