0
0
Reactframework~5 mins

useCallback hook in React

Choose your learning style9 modes available
Introduction

The useCallback hook helps you keep a function the same between renders unless its inputs change. This saves work and avoids mistakes when React checks for changes.

When you want to prevent a function from being recreated every time your component updates.
When you pass a function to a child component that only needs to update if certain data changes.
When you want to avoid extra work in React hooks or components that depend on a function.
When you want to improve performance by reducing unnecessary renders caused by new function references.
Syntax
React
const memoizedFunction = useCallback(() => {
  // function code here
}, [dependencies]);

The first argument is the function you want to keep the same.

The second argument is an array of values that, when changed, will recreate the function.

Examples
This function updates a count and only changes when count changes.
React
const increment = useCallback(() => {
  setCount(count + 1);
}, [count]);
This function never changes because it has no dependencies.
React
const sayHello = useCallback(() => {
  console.log('Hello!');
}, []);
Sample Program

This component shows a count and a button. The increment function is created once and reused, so React won't recreate it on every render. Clicking the button increases the count.

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

function Counter() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment} aria-label="Increment count">Increase</button>
    </div>
  );
}

export default Counter;
OutputSuccess
Important Notes

Using useCallback helps React avoid unnecessary work but don't overuse it; only use when you see performance issues or pass functions to optimized child components.

Remember to include all variables your function uses in the dependency array to keep it updated correctly.

Summary

useCallback keeps a function the same between renders unless dependencies change.

It helps improve performance by avoiding unnecessary function recreations.

Use it when passing functions to child components or hooks that depend on stable functions.