-
3월18일 TIL : automatic batchJava Script & Type Script/TIL 2023. 3. 18. 01:48728x90
폭풍업뎃... 이게 어떻게된거냐면요
코딩애플로 리액트 전체 다시 한번 싹 훑는 중입니다.. 근데 몰랐던 내용도 많고
나는 그동안 아무것도 모르고 코딩하고있었구나....싶네요
라이브러리 없이 애니메이션효과넣는걸 하고있었다.
//App.css .start { opacity: 0; } .end { opacity: 1; transition: opacity 0.5s; }
<div className={"start" + fade}></div> //이렇게도 되고 <div className={`start ${fade}`}></div> //이렇게도 됨
useEffect(()=>{ setFade('end') }, [탭])
그냥 이렇게했을 땐 안되는 이유
classname="start end" 로 만드려는건데, start였다가 start end 이렇게 변경돼야 작동함. 그래서 다시 공백으로 만들어주는 코드가 필요.
setFade("") setFade("end")
이렇게도 안됨. automatic batch 때문에
Automatic Batch이란?
리액트 18버전 이상부터는 automatic batch 라는 기능이 생겼다.
https://immigration9.github.io/react/2021/06/12/automatic-batching-react.html
배칭은 React가 더 나은 성능을 위해 여러 개의 state 업데이트를 하나의 리렌더링 (re-render)로 묶는 것을 의미한다.
예를들어, 하나의 클릭 이벤트 안에 두 개의 state 업데이트를 가지고 있다면, React는 언제나 이 작업을 배칭하여 하나의 리렌더링으로 만들었다. 다음과 같은 코드를 실행해보면, 매 번 누를 때마다, state를 두 번 변경하였지만, React가 단 한 번의 렌더링만 수행한 것을 볼 수 있다.
function App() { const [count, setCount] = useState(0); const [flag, setFlag] = useState(false); function handleClick() { setCount((c) => c + 1); // 아직 리렌더링 하지 않는다 setFlag((f) => !f); // 아직 리렌더링 하지 않는다 // React는 이 함수가 끝나면 리렌더링을 한다 (이것이 배칭이다!) } return ( <div> <button onClick={handleClick}>Next</button> <h1 style=>{count}</h1> </div> ); }
state 변경함수들이 연달아서 여러개 처리되어야한다면 (가까이에 위치)
state 변경함수를 다 처리하고 마지막에 한 번만 재렌더링됩니다.
그래서 'end' 로 변경하는거랑 ' ' 이걸로 변경하는거랑 약간 시간차를 뒀습니다.그러기 위해 setTimeout을 이용했고, setTimeout말고도 flushSync()를 써도 automatic batching을 막을 수 있다.
function TabContent({ tab }) { const [fade, setFade] = useState(""); useEffect(() => { setTimeout(() => { setFade("end"); }, 100); return () => { setFade(""); }; }, [tab]); return <div className={"start " + fade}>{[<div>내용0</div>, <div>내용1</div>, <div>내용2</div>][tab]}</div>; }
728x90'Java Script & Type Script > TIL' 카테고리의 다른 글
3월 26일 TIL : ReactQuery 시작하기 (0) 2023.03.26 3월 23일 TIL : TS-Overloading, Polymorphism [타입스크립트야... 내가 명시도안했는데 타입을 유추한거야?] (0) 2023.03.24 3월 21일 TIL : TypeScript-call signature, unknown,void,never (0) 2023.03.23 3월 18일 TIL : TypeScript 시작 (0) 2023.03.21 3월 18일 TIL : context API, props전송없이 state를 공유하는 방법 (0) 2023.03.18