每天一个hooks学习之useUnmount

引言

useUnmount,组件卸载时执行的 Hook,比如组件卸载时,需要清除定时器或者相关的监听,就可以使用useUnmount。

🦌来看看效果

可以看到,只有在子组件销毁时时,useUnmount才执行了。

🐿源码实现

const useUnmount = (fn: () => void) => {
 const fnRef = useRef(fn);
 fnRef.current = fn;
 useEffect(() => () => fn?.(), []);
};

🐬完整demo源码

import { useEffect, useRef, useState } from "react";
// 自定义useUnmount hooks
const useUnmount = (fn: () => void) => {
 const fnRef = useRef(fn);
 fnRef.current = fn;
 useEffect(() => () => fn?.(), []);
};
const Child = () => {
 useUnmount(() => {
 console.log("子组件销毁了");
 });
 return <div>我是子组件</div>;
};
const UseUnmountDemo = () => {
 const [showChild, setShowChild] = useState(true);
 return (
 <>
 {showChild && <Child />}
 <button onClick={() => setShowChild(!showChild)}>显示销毁子组件</button>;
 </>
 );
};
export default UseUnmountDemo;

🍓参考

有兴趣的小伙伴可以去看,react-useahooks 的源码,学习前辈们优雅的代码

作者:jimmy_fx

%s 个评论

要回复文章请先登录注册