Skip to content

Commit

Permalink
feat: useTransition replace timeout with animationFrameTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
iamyoki committed Dec 22, 2021
1 parent 262e720 commit c59c662
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
1 change: 0 additions & 1 deletion src/useSwitchTransition/useDefaultMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export function useDefaultMode<S>({

// skip fist mount and any unchanged effect 🚫
const [lastItem] = list.slice(-1);
console.log(lastItem.state, state, 'default');
if (lastItem.state === state) return;

// 0 update key
Expand Down
15 changes: 11 additions & 4 deletions src/useTransition/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import {useEffect, useRef, useState} from 'react';
import {
Canceller,
clearAnimationFrameTimeout,
setAnimationFrameTimeout,
} from '../helpers/setAnimationFrameTimeout';

export type Stage = 'from' | 'enter' | 'leave';

Expand All @@ -7,27 +12,29 @@ export function useTransition(state: boolean, timeout: number) {
const [stage, setStage] = useState<Stage>(state ? 'enter' : 'from');

// the timer for should mount
const timer = useRef<number>();
const timer = useRef<Canceller>({});
const [shouldMount, setShouldMount] = useState(state);

useEffect(
function handleStateChange() {
clearTimeout(timer.current);
clearAnimationFrameTimeout(timer.current);

// when true - trans from to enter
// when false - trans enter to leave, unmount after timeout
if (state === true) {
setStage('from');
setShouldMount(true);
setTimeout(() => {
setAnimationFrameTimeout(() => {
setStage('enter');
});
} else {
setStage('leave');
timer.current = setTimeout(() => {
timer.current = setAnimationFrameTimeout(() => {
setShouldMount(false);
}, timeout);
}

return () => clearAnimationFrameTimeout(timer.current);
},
[state, timeout]
);
Expand Down

0 comments on commit c59c662

Please sign in to comment.