Skip to content

Commit

Permalink
feat: almost finished useTransition and Transition
Browse files Browse the repository at this point in the history
  • Loading branch information
iamyoki committed Dec 16, 2021
1 parent 9553a82 commit a540689
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 4 deletions.
5 changes: 3 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
},
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
}
},
"editor.formatOnSave": true
}
13 changes: 13 additions & 0 deletions src/Transition.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {Stage, useTransition} from './useTransition';

type TransitionProps = {
state: boolean;
timeout: number;
children: (stage: Stage, shouldMount: boolean) => React.ReactNode;
};

export function Transition({state, timeout, children}: TransitionProps) {
const {stage, shouldMount} = useTransition(state, timeout);

return children(stage, shouldMount);
}
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
console.log('init project for npm package register');
export {};
export {useTransition} from './useTransition';
export {Transition} from './Transition';
39 changes: 39 additions & 0 deletions src/useTransition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {useEffect, useRef, useState} from 'react';

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

export function useTransition(state: boolean, timeout: number) {
// the stage of transition - 'from' | 'enter' | 'leave'
const [stage, setStage] = useState<Stage>(state ? 'enter' : 'from');

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

useEffect(
function handleStateChange() {
clearTimeout(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(() => {
setStage('enter');
});
} else {
setStage('leave');
timer.current = setTimeout(() => {
setShouldMount(false);
}, timeout);
}
},
[state, timeout]
);

return {
stage,
shouldMount,
};
}

0 comments on commit a540689

Please sign in to comment.