Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

React useCallback Hook



The useCallback hook in React is used to memoize functions, preventing them from being recreated on every render. This can be useful for performance optimization, particularly when passing callback functions to child components that rely on reference equality to prevent unnecessary renders.

Basic Usage of useCallback

The useCallback hook takes two arguments:

  1. A function to memoize.
  2. An array of dependencies.

The memoized function will only be recreated if one of the dependencies has changed.



        
        import React, { useState, useCallback } from 'react';

        const MyComponent = () => {
          const [count, setCount] = useState(0);
          const [text, setText] = useState('');
        
          const increment = useCallback(() => {
            setCount(c => c + 1);
          }, []); // No dependencies, so this function will never be recreated.
        
          const updateText = useCallback((newText) => {
            setText(newText);
          }, [text]); // Only recreated if `text` changes.
        
          return (
            <div>
              <button onClick={increment}>Increment: {count}</button>
              <input
                type="text"
                value={text}
                onChange={e => updateText(e.target.value)}
              />
            </div>
          );
        };
        
        export default MyComponent;
      

Example: useCallback with Child Components

Consider a scenario where you have a parent component passing a callback to a child component. Using useCallback ensures the callback is not recreated on every render, thus avoiding unnecessary renders of the child component.

Parent Component



        // ParentComponent.js
        import React, { useState, useCallback } from 'react';
        import ChildComponent from './ChildComponent';
        
        const ParentComponent = () => {
          const [count, setCount] = useState(0);
        
          const increment = useCallback(() => {
            setCount(c => c + 1);
          }, []);
        
          return (
            <div>
              <button onClick={increment}>Increment: {count}</button>
              <ChildComponent onIncrement={increment} />
            </div>
          );
        };
        
        export default ParentComponent;
      </code>
    </pre>
    <br>
    <h5>Child Component</h5>
    <br>
    <pre class="version">
        // ChildComponent.js
        import React from 'react';
  
        const ChildComponent = React.memo(({ onIncrement }) => {
          console.log('Child component rendered');
          return (
            <div>
              <button onClick={onIncrement}>Increment from Child</button>
            </div>
          );
        });
        
        export default ChildComponent;
        

In this example, the ChildComponent will only re-render if the onIncrement function changes. Since useCallback is used, the onIncrement function is memoized and only changes if the dependencies (which are none in this case) change.

When to Use useCallback

When Not to Use useCallback





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

Zava

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

Zava