Skip to content

Instantly share code, notes, and snippets.

@srph
Last active July 29, 2019 14:51
Show Gist options
  • Save srph/bd6b145ef983a03acfd175853ff6855b to your computer and use it in GitHub Desktop.
Save srph/bd6b145ef983a03acfd175853ff6855b to your computer and use it in GitHub Desktop.
React: Access updated props inside custom event listeners

Use-case

This is particularly useful if you have to attach to a document event (in my case, a keyboard event). Unless you re-attach the event whenever anything changes, you will have stale props. Now, we don't want that, do we?

In my case, I had a hook which accepted this argument:

interface Props {
  isDisabled: () => boolean
  onToggleChat: () => void
  onToggleMute: () => void
  onFullscreen: () => void
  onFullscreenExit: () => void
  onPlay: () => void
  onForward: () => void
  onBackward: () => void
}

Usage

function usePlayerHotkeys(props: Props) {
  const props = usePropRef(hookProps)
  
  useEffect(() => {
    function handleKeyDown() {
      //
    }
    
    document.addEventListener('keydown', handleKeyDown)

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }, [])
}
import { useEffect, useRef } from 'react'
/**
* Useful if you need access to your props in a custom document event listener.
*
* Unless you re-attach the events everytime your props change
* (which is a deal breaker if you have object parameters),
* you will get stale props (usually from the first mount).
*
* @usage const props = usePropRef(hookProps)
*/
function usePropRef<T = any>(props: T) {
const propRef = useRef<T>(props)
useEffect(() => {
propRef.current = props
}, [props])
return propRef.current
}
export default usePropRef
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment