Skip to content

Instantly share code, notes, and snippets.

@EddiG
Last active February 23, 2022 08:11
Show Gist options
  • Save EddiG/7961f5798904f8c6d99eca2536e27414 to your computer and use it in GitHub Desktop.
Save EddiG/7961f5798904f8c6d99eca2536e27414 to your computer and use it in GitHub Desktop.
Contains React Hooks those I found useful

useDebounce

https://epicreact.dev/the-latest-ref-pattern-in-react/

function useDebounce(callback, delay) {
  // Using the useRef allows us to avoid any re-renders when the callback changes
  const callbackRef = React.useRef(callback)
  
  // The useLayoutEffect will be run before any other code, so that
  // we will have always latest callback function called in the debounce 
  // payload function.
  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })
  
  return React.useMemo(
    () => debounce((...args) => callbackRef.current(...args), delay),
    [delay],
  )
}

Trigger component re-render on ref changes

https://reactjs.org/docs/refs-and-the-dom.html#callback-refs

function SomeComponent() {
  const [container, setContainer] = React.useState(null)
  
  React.useEffect(() => {
    if (!container) {
      return
    }
    
    // do something with the container (DOM element)
  }, [container])
  
  return (<div ref={node => setContainer(node)}>content</div>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment