React Hooks | Why useCallback ?
Tags: react, usecallback, hooks, memoization
Published: 2021-04-24 19:17:17

## The Problem
Functions are [First-class](https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function) 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.
```js
// 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.

```js
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9f1rvlnqgy5a5hhek94q.png)
 
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
```js
  // const saveText = () => {
  //   window.localStorage.setItem("name", name);
  // };

  const saveText = React.useCallback(() => {
    window.localStorage.setItem("name", name);
  }, [name]);
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nncdc2hhswxu0nuzd6gu.png)
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 :**

{% codesandbox egrwl %}

---