Tuesday, 5 August 2025

React useCallback Hook



We'll use useCallback to :

  • Passing a function as prop to React.memo child
  • Prevents unnecessary re-renders
  • Setting up event handlers inside components
  • Prevents recreation of handler functions
  • Functions inside useEffect/useMemo that need stable reference
  • Avoids infinite loops or unnecessary logic execution
Example : 

import React, { useCallback, useState } from 'react';
import './App.css';
import Dashboard from './component/Dashboard';

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

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

  const handleClick = useCallback(() => {
    console.log('Clicked');
  }, []);

  return (
    <div className="App">
      <Dashboard />
      <h2>React useCallback Example</h2>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <Child onClick={handleClick} />
    </div>
  );
}

export default App;

No comments:

Post a Comment