/** * title: 基础用法 * desc: 通过 usePersistFn,函数引用永远不会变化,示例中 showCountPersistFn 是不会变化的,showCountCommon 在 count 变化时变化。 */ import React, { useState, memo, useRef, useCallback } from 'react'; import { message } from 'antd'; import { usePersistFn } from 'yhooks'; export default () => { const [count, setCount] = useState(1); const showCountPersistFn = usePersistFn(() => { message.info(`Current count is ${count}`); }); const showCountCommon = useCallback(() => { message.info(`Current count is ${count}`); }, [count]); return ( <>

使用usePersistFn 跟useCallback的区别

Component with persist function:

{/* use persist function, ExpensiveTree component 不会重新render, 但能获取到count最新值 */}

Component without persist function:

{/* without persist function, ExpensiveTree component count更新, 组件重新render */}
); }; // some expensive component with React.memo const ExpensiveTree = memo<{ [key: string]: any }>(({ showCount }) => { const renderCountRef = useRef(0); renderCountRef.current += 1; return (

Render Count: {renderCountRef.current}

); });