React Hooks | Why useCallback ?

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
( () => {} ) …


This content originally appeared on DEV Community and was authored by bhupendra

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
image

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 = () => {
  //   window.localStorage.setItem("name", name);
  // };

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

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


This content originally appeared on DEV Community and was authored by bhupendra


Print Share Comment Cite Upload Translate Updates
APA

bhupendra | Sciencx (2021-04-24T19:17:17+00:00) React Hooks | Why useCallback ?. Retrieved from https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/

MLA
" » React Hooks | Why useCallback ?." bhupendra | Sciencx - Saturday April 24, 2021, https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/
HARVARD
bhupendra | Sciencx Saturday April 24, 2021 » React Hooks | Why useCallback ?., viewed ,<https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/>
VANCOUVER
bhupendra | Sciencx - » React Hooks | Why useCallback ?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/
CHICAGO
" » React Hooks | Why useCallback ?." bhupendra | Sciencx - Accessed . https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/
IEEE
" » React Hooks | Why useCallback ?." bhupendra | Sciencx [Online]. Available: https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/. [Accessed: ]
rf:citation
» React Hooks | Why useCallback ? | bhupendra | Sciencx | https://www.scien.cx/2021/04/24/react-hooks-why-usecallback/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.