useRef, useMemo & useCallback- get the difference
Often there is lot of confusion between these hooks, lets look at these one by one.
useRef - A hook which can store a mutable value, which does not re-render the view on update. Also it can be used to store DOM elements
It creates a mutable object which holds a .current property . It is often used to directly access DOM elements or to store any mutable value that doesn't trigger a re-render when changed
const inputRef = useRef(null);
const focusInput = () => {inputRef.current.focus()};
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</>
)
useMemo - A function which only gets called everytime a specific state changes. Works great for memoizing returned values
useCallback - It works exactly like useMemo but instead of returning a value it returns a function
Use useCallback when you have a function that needs to maintain a stable reference between renders, especially when it’s passed as a prop to child components or used inside useEffect or useMemo.