techStackGuru

React useCallback Hook


React uses the useCallback hook to memoize callbacks and prevent unnecessary re-renders for component children that depend on them. This method returns a memoized callback function that only changes if any of the dependencies change.

Example

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

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

  // Define the callback function using useCallback
  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default ExampleComponent; 

Here, we have a functional component called ExampleComponent that renders a button and a count value. Using the useState hook, the count state is initialized to 0. By using useCallback, the handleClick function is defined. As soon as it is called, the count state is incremented. The second argument to useCallback specifies when the callback should be memoized based on the dependencies. As a result, we pass an empty array [], which indicates that the callback should only ever be created once during the initial render.

Here's another example

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

const ExampleComponent = () => {
  const [text, setText] = useState('');

  // Define the callback function using useCallback
  const handleChange = useCallback((event) => {
    setText(event.target.value);
  }, []);

  return (
    <div>
      <input type="text" value={text} onChange={handleChange} />
      <p>Typed text: {text}</p>
    </div>
  );
};

export default ExampleComponent; 

Here, we have an input field for users to type text into. The useState hook is used to store typed text in the text state.

UseCallback is used to define the handleChange function. Text state is updated with value entered in input field. The handleChange function requires the text state, so we pass it as a dependency to useCallback as the second argument.

This dependency will cause handleChange to be memoized and recreated only if the text state changes. As a result, this prevents unnecessary re-rendering of child components that rely on this callback.