From 74838a9ba73968d15be45fa8a986dfc5501286ed Mon Sep 17 00:00:00 2001 From: sabertazimi Date: Tue, 10 Aug 2021 03:31:21 +0800 Subject: [PATCH] feat(hooks): move typing logic to useTypingEffect hook --- src/hooks/index.ts | 1 + src/hooks/useTypingEffect.ts | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/hooks/useTypingEffect.ts diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 6e4eaede8..fef36c42b 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -2,4 +2,5 @@ export { default as useBuildTime } from './useBuildTime'; export { default as useDisqus } from './useDisqus'; export { default as usePostsMetadata } from './usePostsMetadata'; export { default as useSiteMetadata } from './useSiteMetadata'; +export { default as useTypingEffect } from './useTypingEffect'; export { default as useVisibility } from './useVisibility'; diff --git a/src/hooks/useTypingEffect.ts b/src/hooks/useTypingEffect.ts new file mode 100644 index 000000000..aefd36f5c --- /dev/null +++ b/src/hooks/useTypingEffect.ts @@ -0,0 +1,40 @@ +import { RefObject, useEffect, useRef } from 'react'; +import Typed from 'typed.js'; + +interface TypingOptions { + titles: string[]; + speed: number; + delay: number; + loop: boolean; +} + +const useTypingEffect = ( + ref: RefObject, + options: TypingOptions +): void => { + const { titles, speed, delay, loop } = options; + const typed = useRef(null); + + useEffect(() => { + const options = { + strings: [...titles], + smartBackspace: true, + typeSpeed: speed, + backSpeed: speed, + backDelay: delay, + loop, + }; + + if (ref.current) { + typed.current = new Typed(ref.current, options); + } + + return () => { + if (typed.current) { + typed.current.destroy(); + } + }; + }, [ref, titles, speed, delay, loop]); +}; + +export default useTypingEffect;