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?