본문 바로가기
개발/React

[React] useTransition 알아보기

by 그레이웅 2023. 3. 26. 23:18
반응형

useTreansition hook api

 

useTransition은 React 18에 들어오면서 새로 도입된 함수이다.

 

바로 공식문서의 예제를 보면서 정리하겠다.

 

function App() {
  const [isPending, startTransition] = useTransition();
  const [count, setCount] = useState(0);
  
  function handleClick() {
    startTransition(() => {
      setCount(c => c + 1);
    });
  }

  return (
    <div>
      {isPending && <Spinner />}
      <button onClick={handleClick}>{count}</button>
    </div>
  );
}

 

useTreansition 함수의 반환값은 isPending , startTransition 으로 설정된다.

isPending은 현재 작업이 지연되고 있음을 boolean 형태로 알리게 된다.

isPending은 현재 상태에 대한 상태 저장값을 저장하고,

 

startTransition은 다음과 같이 콜백 함수를 감싸준다.

startTransition(() => {
  setCount(count + 1);
});

stratTransition은 집중되는 프로세스를 감싸주어서 그 함수의 지연여부를 판단하고, 그 상태값이 isPending에 저장되어 완료되면 상태가 변경되어 완료 전에는 스피너가 돌고, 그 이후는 결과가 보이는 형태가 된다.

 

무겁고, 우선순위가 낮은 API에 해당 startTranition함수를 걸어주어 state가 변환되는 시점까지

해당 isPending을 사용하여 스피너나 로딩바 같은 걸 걸어준다면 , 사용자 경험도 향상할 수 있을 것이다.

 

React 공식문서에는 내가 알지못하는 새로 만들어진 hook이나 기술들이 아직 많다.

잘 정리해가며 한번씩 사용해 보는것이 내 개발 커리어에 도움이 많이되고있다.

이것도 도입해봐야지!

 

 

- https://ko.reactjs.org/docs/hooks-reference.html#usetransition

- https://dev.to/sameer1612/react-v18-usetransition-hook-why-3bml

반응형

댓글