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

In React rendering means creating react elements and displaying on screen , this can be caused by state change, context change or a parent re-render. This is will cause re-run of the functional Component which will cause any function inside the Component to be destroyed (Garbage Collected) and created again on each re-render.

Example

Below Component renders a Text and button fields. value from the text field is saved to localStorage onChange.

import React from "react"

const fnCount = new Set() // stores only unique values

export default function App() {
  const [name, setName] = React.useState(
    () => window.localStorage.getItem("name") || ""
  )
  const [count, setCount] = React.useState(0)

  const saveText = () => {
    window.localStorage.setItem("name", name)
  }

  React.useEffect(() => {
    saveText()
  }, [saveText])

  fnCount.add(saveText) // keeps count of times new fn created
  console.log(fnCount)

  return (
    <div className="App">
      <h1>Understanding useCallback</h1>
      <input
        type="text"
        value={name}
        onChange={e => setName(e.target.value)}
        placeholder="Your Name :"
      />
      <button
        onClick={() => {
          setCount(c => c + 1)
        }}
      >
        Count:{count}
      </button>
    </div>
  )
}

In above code fnCount is a Set so it will keep track of number of times function saveText is created on each re-render of App component triggered on change of Input field.

Below is the console log after 3 button clicks

useCallback example 1

On Component mount, fnCount had one 1 entry but on each re-render of component saveText fn is re-initialized and is brand new so now fnCount has 4 entries (1 + 3 for each re-render). Since saveText is related to name state so should not be re-run on button click. This is the problem useCallback solves by not letting React to initialize function on each render unless dependencies in useCallback changes.

Solution

const saveText = React.useCallback(() => {
  window.localStorage.setItem("name", name)
}, [name])

useCallback example 2

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 :