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

时间:2020-05-11 09:14:54

标签: reactjs react-hooks memoization

如果我使用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
    }
}

1 个答案:

答案 0 :(得分:1)

除非将对象直接传递给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} />
   )
}