我应该记住自定义React钩子的返回对象吗?

If I used useCallback for the methods of my custom hook, should I also memoize the returned object? I would assume that it would not create a new object everytime since it's composed with memoized methods and primitives.

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函数,否则您无需记住返回的对象,在这种情况下引用将失败

    但是,如果您像这样使用它

    const Comp = () => {
       const { toggleOn, toggleOff } = useToggle();
    
       useEffect(() => {
          console.log('Something here')
       }, [toggleOn]);  
       return (
           <Child toggleOn={toggleOn} toggleOff={toggleOff} />
       )
    }
    

    You don't need to add an extra layer of memoization over useCallback

    但是,像下面的代码这样的用法将需要记忆返回的对象

    const Comp = () => {
       const toggle = useToggle();
    
       useEffect(() => {
          console.log('Something here')
       }, [toggle]);  
       return (
           <Child toggleHandlers={toggle} />
       )
    }