How To Use useCallback Hook In React? See Example

The useCallback hook memoizes a function so it is only recreated when dependencies change.
It helps prevent unnecessary re-renders of child components.


Basic Syntax

const memoizedCallback = useCallback(() => {
  // function logic
}, [dependencies]);
  • Function is recreated only when dependencies change
  • Useful when passing functions to child components

Example: Prevent Unnecessary Re-renders

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

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

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

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <h2>Other: {other}</h2>
      <Button handleClick={increment} />
      <button onClick={() => setOther(other + 1)}>Increment Other</button>
    </div>
  );
}

export default App;

Button does not re-render when other changes because increment is memoized.


Key Points

  • Memoizes functions
  • Prevents unnecessary child re-renders
  • Works with React.memo
  • Dependencies determine when function is recreated

Conclusion

useCallback improves performance in React apps by stabilizing functions, especially when passing them to memoized child components.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *