HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React useCallback Hook

React useCallback

'useCallback' is a React Hook that memoizes a callback function, preventing it from being recreated on every render.

This can be useful to optimize performance, especially in scenarios where callbacks are passed down to child components.

Here's a basic example of how to use 'useCallback':

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

const MyComponent = () => {
const [count, setCount] = useState(0);

// Regular callback function
const handleClick = () => {
setCount(count + 1);
};

// Memoized callback using useCallback
const memoizedHandleClick = useCallback(() => {
setCount(count + 1);
}, [count]); // Dependency array, re-create the callback only when 'count' changes

return (
<div>
<p>Count: {count}</p>

{/* Regular callback */}
<button onClick={handleClick}>Increment</button>

{/* Memoized callback */}
<button onClick={memoizedHandleClick}>Increment Memoized</button>
</div>
);
};

export default MyComponent;

In this example

  • 'handleClick' is a regular callback function created inside the component.
  • 'memoizedHandleClick' is a memoized callback created using 'useCallback'. The second argument of 'useCallback' is an array of dependencies, and the memoized callback will only be recreated if any of the dependencies change.