Full Stack Development

useCallback

by Tomas Trescak t.trescak@westernsydney.edu.au

useCallback

Why useCallback?

  • Unnecessary re-renders of child components.
  • Performance issues in complex apps

useCallback

How useCallback works?

    const memoizedCallback = useCallback(() => {
  // Your function logic here
}, [dependencies]);
  

useCallback

/

Basic Example

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

const Child = React.memo(({ onClick }) => {
  console.log("Child rendered");
  return <button onClick={onClick}>Click Me</button>;
});

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

  const handleClick = () => {
    console.log("Button clicked");
  };

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

render(<Parent />)
    

useCallback

/

Advanced Example

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

const Child = React.memo(({ onClick }) => {
  console.log("Child rendered");
  return <button onClick={onClick}>Log Count</button>;
});

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

  const handleClick = useCallback(() => {
    console.log(`Count: ${count}`);
  }, [count]); // Recreate the function only if `count` changes

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

render(<Parent />)
    

useCallback

When to use

  • Passing Functions as Props:
    • Prevent unnecessary re-renders of memoized child components.
  • Event Handlers:
    • Optimize frequently used handlers like onClick, onChange, etc.
  • Expensive Functionality:
    • Memoize expensive functions that are called repeatedly in the render cycle.

useCallback

When not to use

  • Overuse: Don’t wrap every function in useCallback. Use it only when there’s a clear performance benefit.

  • Simple Apps: In small apps, function recreation is rarely a performance bottleneck.

useCallback

Summary

  • Purpose: Memoize functions to prevent unnecessary re-creations and improve performance.
  • Syntax: useCallback(() => {...}, [dependencies])
  • Key Use Cases: Prevent child re-renders, optimize event handlers, memoize expensive functions.
  • Caution: Use it judiciously; overuse can complicate code without significant benefits.