how to handle rest arguments and function in useeffect causing re-render

According to your needs, I divide the dependency into two parts for analysis.

  1. args

args is an array and will be brand new each time.

Consider creating a useCustorCompareEffect. By customizing the comparison function. The effect will actually be triggered only when the specified value changes.

Edit useCustorCompareEffect Demo

const useCustorCompareEffect = (callback, value, compare) => {
  const prev = useRef({ init: true, value })
  useEffect(() => {
    const { current } = prev
    if (current.init) {
      callback()
      current.init = false
    } else {
      if (!compare || !compare(value, current.value)) {
        callback()
        current.value = value
      }
    }
  }, [callback, value, compare])
}

const useDemo=()=>{
  const compare = useCallback((curr, prev) => {
    // Compare functions, return comparison results, use `useCallback` to prevent triggering `effect` due to compare
  }, [])

  useCustorCompareEffect(
    () => {
      ...
    },
    [data],
    compare,
  )
}
  1. fn

To use a function as a dependency, you can wrap the function definition in useCallback and then define the dependencies required by this function in useCallback.


const execute = useCallback(() => {
  console.log('update')
}, [])

useEffect(() => {
  execute()
}, [execute);

In your case, your function is obtained by another useWrappedRemoteCall, which needs to use the useCallback package execute definition in useWrappedRemoteCall and then return. In addition, if you only use execute in useEffect, you need to extract execute and then use execute as a dependency. To prevent other data changes in fn from triggering effect

const useWrappedRemoteCall = () => {
  const execute = useCallback(() => {
    console.log('update')
  }, [])
  return { execute }
}
const usePagedGetAll = () => {
  const { execute } = useWrappedRemoteCall()
  useEffect(() => {
    execute()
  }, [execute])
}

If there are other special circumstances, please let me know.

Tags:

Reactjs