Optimize React Components with useCallback()
Tags: react, javascript, webdev, programming
Published: 2024-05-21 10:04:20

In this post, we'll explore the powerful `useCallback` hook in React, which allows you to optimize your components by memoizing functions. By using `useCallback`, you can prevent unnecessary re-creation of functions during renders, leading to better performance.

## What is `useCallback`?

The `useCallback` hook is all about efficiency. It helps you memoize functions so that they are only re-created when their dependencies change. Imagine having a smart assistant who remembers the answers to math problems—`useCallback` does something similar for your functions in React. Let's dive into an example to see how it works.

## Example: Increment Counter

Suppose we have a simple counter app with two buttons: one to increment the counter and another to toggle its visibility. Here's the initial implementation without `useCallback`:

```jsx
import React, { useState } from 'react';

function Button(props) {
  return <button onClick={props.onClick}>{props.name}</button>;
}

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

  const handleCount = () => setCount(count + 1);
  const handleShow = () => setActive(!isActive);

  return (
    <div className="App">
      {isActive && (
        <div>
          <h1>{count}</h1>
          <Button onClick={handleCount} name="Increment" />
        </div>
      )}
      <Button
        onClick={handleShow}
        name={isActive ? 'Hide Counter' : 'Show Counter'}
      />
    </div>
  );
}

export default App;
```

In the above code, every time we click a button, the UI updates, and both `handleCount` and `handleShow` functions are re-created. To optimize this, we'll wrap our functions with `useCallback`:

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

function Button(props) {
  return <button onClick={props.onClick}>{props.name}</button>;
}

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

  const handleCount = useCallback(() => setCount(count + 1), [count]);
  const handleShow = useCallback(() => setActive(!isActive), [isActive]);

  return (
    <div className="App">
      {isActive && (
        <div>
          <h1>{count}</h1>
          <Button onClick={handleCount} name="Increment" />
        </div>
      )}
      <Button
        onClick={handleShow}
        name={isActive ? 'Hide Counter' : 'Show Counter'}
      />
    </div>
  );
}

export default App;
```

By wrapping our functions with `useCallback`, we ensure that they are only re-created if their dependencies (in this case, `count` and `isActive`) change. Now, clicking the "Increment" button updates the count value without unnecessary function re-creation.

## When to Use `useCallback`?

Here are some scenarios where you might want to use `useCallback`:

- **Event Handlers**: When passing event handlers to child components.
- **Memoizing Expensive Computations**: For functions that perform heavy calculations.
- **Optimizing Performance**: To prevent unnecessary re-renders.

Remember to choose the right dependencies and avoid overusing `useCallback`. Measure performance to ensure you're getting the desired optimization¹. Now you're ready to supercharge your React components with `useCallback`! 🚀

Source: Conversation with Copilot, 21/5/2024
(1) How to use React useCallback hook with examples | Reactgo. https://reactgo.com/react-usecallback-hook/.
(2) React useCallback Hook - W3Schools. https://www.w3schools.com/react/react_usecallback.asp.
(3) Understanding useCallback Hook in React: Best Practices and Examples. https://www.codinn.dev/articles/react-usecallback-hook-explained-with-examples.
(4) Understanding useCallback Hook in React: Best Practices and Examples .... https://medium.com/@mohammedsafir17/understanding-usecallback-hook-in-react-best-practices-and-examples-dfea3af6f779.
(5) How to use useCallback() hook. Improve your React components… | by .... https://medium.com/@dev_one/how-to-use-usecallback-hook-35dc047aee48.
(6) Memoization in React - How useCallback Works | Refine. https://refine.dev/blog/react-usecallback-guide/.
(7) useCallback: Guide, use-cases, examples. https://deadsimplechat.com/blog/usecallback-guide-use-cases-and-examples/.
(8) Demystifying React’s useCallback Hook: A Comprehensive Guide. https://medium.com/@sakshithakare121/demystifying-reacts-usecallback-hook-a-comprehensive-guide-4a0c600a0c79.
(9) github.com. https://github.com/Shri12345patil/React-Topics/tree/8f08d7abc5376fd7fc70ca01104505d6776a2bbb/35-useCallback%20example%2Fsrc%2FApp.js.
(10) github.com. https://github.com/heticeric/react_16x-courses/tree/bc3af9918b71b09c6b81de5a0edc20057a6003f3/hooks%2Fmemoization.md.