SHARE
TWEET

Untitled

a guest Oct 22nd, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, {useCallback, useRef} from 'react'
  2.  
  3. function useHookWithRefCallback() {
  4.   const ref = useRef(null)
  5.   const setRef = useCallback(node => {
  6.     if (ref.current) {
  7.       // Make sure to cleanup any events/references added to the last instance
  8.     }
  9.    
  10.     if (node) {
  11.       // Check if a node is actually passed. Otherwise node would be null.
  12.       // You can now do what you need to, addEventListeners, measure, etc.
  13.     }
  14.    
  15.     // Save a reference to the node
  16.     ref.current = node
  17.   }, [])
  18.  
  19.   return [setRef]
  20. }
  21.  
  22. function Component() {
  23.   // In your component you'll still recieve a `ref`, but it
  24.   // will be a callback function instead of a Ref Object
  25.   const [ref] = useHookWithRefCallback()
  26.  
  27.   return <div ref={ref}>Ref element</div>
  28. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top