Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active May 20, 2020 14:01
Show Gist options
  • Save ryanflorence/02162f8660201987bf9fde0172aa75c6 to your computer and use it in GitHub Desktop.
Save ryanflorence/02162f8660201987bf9fde0172aa75c6 to your computer and use it in GitHub Desktop.
// I've only used this for focus management, I'm willing to bet you don't
// actually want to do this unless it's focus management
function useUpdateEffect(effect, deps) {
let mounted = useRef(false)
useEffect(() => {
if (mounted.current) {
return effect()
} else {
mounted.current = true
}
}, deps) // linter will hate you but whatev
}
@ryanflorence
Copy link
Author

useUpdateEffect(() => {
  console.log("your code has updated from the original value")
}, [props.code])

@ryanflorence
Copy link
Author

Could do it this way too:

function Thing({ code }) {
  let firstCode = useRef(code)
  useEffect(() => {
    if (code === firstCode.current) {
      return
    } else {
      doYourThing()
    }
  }, [code])
}

@ryanflorence
Copy link
Author

Oh, duh, that is exactly what you had in your tweet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment