React Hooks | Why useCallback ?
•3 min read
The Problem
Functions are First-class citizens/objects in JS , which simply means they behave like objects , functions can be ~ stored in variable , passed as argument or returned from a function.
// Referential Equality
( () => {} ) === ( () => {} ) // false
{ greeting:"Hi"} === { greeting:"Hi"} //false
▶Components Re-rendering
▶Example
Solution
const saveText = React.useCallback(() => {
window.localStorage.setItem("name", name)
}, [name])

After wrapping saveText fn with useCallback , function count for saveText remains 1 in fnCount (mount time) after 3 clicks. Since on button Click no dependencies of saveText is changed so useCallback returns the memoized (or memorized) function , that was returned last time.
Example :
