Home > Back-end >  Difference between React useRef and global variable in this situation
Difference between React useRef and global variable in this situation

Time:10-04

Case 1 : using let variable outside of function component

https://codepen.io/evan-jin/pen/VwWOPJV?editors=0010

Case 2 : using React.useRef in Parent function component

https://codepen.io/evan-jin/pen/VwWOpvg?editors=0010

Case 1

let cursorTimer = null  // << this is the point for 1 case

const Item = ({ num }) => {
    const [hoverItem, setHoverItem] = useState(null)
  
  const addCursor = useCallback(() => {
    clearTimeout(cursorTimer)
    cursorTimer = null
    
    cursorTimer = setTimeout(() => {
      document.body.style.cursor = 'wait'
    }, 10)
  }, [])
  
  const removeCursor =  useCallback(() => {
    if (cursorTimer === null) return
    
    cursorTimer = setTimeout(() => {
      document.body.style.cursor = 'grab'
    }, 500)
  }, [])
  
  useEffect(() => {
    hoverItem ? addCursor() : removeCursor()
  }, [hoverItem])

  ...

Case 2

const Item = ({ num, cursorTimerRef }) => {
    const [hoverItem, setHoverItem] = useState(null)
  
  const addCursor = useCallback(() => {
    clearTimeout(cursorTimerRef.current)
    cursorTimerRef.current = null
    
    cursorTimerRef.current = setTimeout(() => {
      document.body.style.cursor = 'wait'
    }, 10)
  }, [])
  
  const removeCursor =  useCallback(() => {
    if (cursorTimerRef.current === null) return
    
    cursorTimerRef.current = setTimeout(() => {
      document.body.style.cursor = 'grab'
    }, 500)
  }, [])
  
  useEffect(() => {
    hoverItem ? addCursor() : removeCursor()
  }, [hoverItem])

  ...

I'm really wondering the difference between this same results.

Since Declaring and using 'let' variable outside of component won't trigger re-rendering components, It gives me the same result as using React useRef that also doesn't trigger re-rendering but can change status in Component.

I tried to find and research on Google, but I couldn't find a proper solution for my question. I don't know which one is better to use and efficient.

Could please someone save my life?

CodePudding user response:

It is working perfectly well and that is expected.

Quoting this from react docs

Avoid using refs for anything that can be done declaratively.

Refs are a thing in React because not everything can be solved declaratively. What you have here cannot be done in a declarative way. So you have to use refs. Using global variable to do this okay, and fine but I'd recommend using refs, because they offer a simpler and more React-y way to do things.

Also, global variables will quickly pollute and cause memory leaks in your application which is clearly not the case when using refs.

  • Related