DEV Community

Discussion on: How to mimic componentDidUpdate() with React Hooks

Collapse
 
devhammed profile image
Hammed Oyedele • Edited

How about converting this to a custom hook?

import React, { useRef, useEffect, useState } from 'react'

// I also made it to support running when specific values update in deps
// The default value for deps will be undefined if you did not pass it
// and will have the same effect as not passing the parameter to useEffect
// so it watch for general updates by default
function useDidUpdate (callback, deps) {
  const hasMount = useRef(false)

  useEffect(() => {
    if (hasMount.current) {
      callback()
    } else {
      hasMount.current = true
    }
  }, deps)
}

// Usage:

function App () {
  useDidUpdate(() => {
    doStuff()
  })
}

// Or:

function AppTwo () {
  const [count, setCount] = useState(0)

  useDidUpdate(() => {
    doStuffIfCountUpdates()
  }, [count])
}
Enter fullscreen mode Exit fullscreen mode

✌️✌️✌️

Collapse
 
mattnmayson profile image
Matt Mayson

Wow guys that really solved a problem i had.. useeffect doesn't imitate componentDidUpdate even after using prop as the last parameter , i used Hammeds solution with useDidUpdate and i just added a prevprops var . seems to be working fine so far.