Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement