DEV Community

Cover image for React Hooks | Why useCallback ?

React Hooks | Why useCallback ?

I am front end developer. I love exploring JS through IOT (Nodebots) , WebVR. Passionate about Web Performance , React & Graph QL
・2 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
Enter fullscreen mode Exit fullscreen mode

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.


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]);

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

  return (
    <div className="App">
      <h1>Understanding useCallback</h1>
        onChange={(e) => setName(}
        placeholder="Your Name :"
        onClick={() => {
          setCount((c) => c + 1);

Enter fullscreen mode Exit fullscreen mode

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

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.


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

  const saveText = React.useCallback(() => {
    window.localStorage.setItem("name", name);
  }, [name]);
Enter fullscreen mode Exit fullscreen mode

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 App :

Discussion (0)