我应该记住自定义 React 钩子的返回对象吗?
Should I memoize the returned object of a custom React hook?
如果我将 useCallback
用于自定义挂钩的方法,我是否也应该记住返回的对象?我假设它不会每次都创建一个新对象,因为它是由记忆方法和基元组成的。
export const useToggle = (args: UseToggleProps) => {
const initialState=
args.initialState !== undefined ? args.initialState : false
const [active, setActive] = useState(initialState)
const toggleOff = useCallback(() => {
setActive(false)
}, [])
const toggleOn = useCallback(() => {
setActive(true)
}, [])
const toggle = useCallback(() => {
setActive((active) => !active)
}, [])
// Should this also be memoized with useMemo?
return {
active,
toggle,
toggleOff,
toggleOn
}
}
您不需要记忆返回的对象,除非您将对象直接传递给 useEffect 的函数,在这种情况下引用将失败
如果您这样使用它,则无需在 useCallback
上添加额外的记忆层:
const Comp = () => {
const { toggleOn, toggleOff } = useToggle();
useEffect(() => {
console.log('Something here')
}, [toggleOn]);
return (
<Child toggleOn={toggleOn} toggleOff={toggleOff} />
)
}
但是像下面代码这样的用法需要对返回的对象进行记忆
const Comp = () => {
const toggle = useToggle();
useEffect(() => {
console.log('Something here')
}, [toggle]);
return (
<Child toggleHandlers={toggle} />
)
}
如果我将 useCallback
用于自定义挂钩的方法,我是否也应该记住返回的对象?我假设它不会每次都创建一个新对象,因为它是由记忆方法和基元组成的。
export const useToggle = (args: UseToggleProps) => {
const initialState=
args.initialState !== undefined ? args.initialState : false
const [active, setActive] = useState(initialState)
const toggleOff = useCallback(() => {
setActive(false)
}, [])
const toggleOn = useCallback(() => {
setActive(true)
}, [])
const toggle = useCallback(() => {
setActive((active) => !active)
}, [])
// Should this also be memoized with useMemo?
return {
active,
toggle,
toggleOff,
toggleOn
}
}
您不需要记忆返回的对象,除非您将对象直接传递给 useEffect 的函数,在这种情况下引用将失败
如果您这样使用它,则无需在 useCallback
上添加额外的记忆层:
const Comp = () => {
const { toggleOn, toggleOff } = useToggle();
useEffect(() => {
console.log('Something here')
}, [toggleOn]);
return (
<Child toggleOn={toggleOn} toggleOff={toggleOff} />
)
}
但是像下面代码这样的用法需要对返回的对象进行记忆
const Comp = () => {
const toggle = useToggle();
useEffect(() => {
console.log('Something here')
}, [toggle]);
return (
<Child toggleHandlers={toggle} />
)
}