DEV Community

Discussion on: The useCallback react hook

Collapse
 
edriso profile image
Mohamed Idris

Common use case: Solving the Re-render Issue with useCallback Hook

In React, using useEffect to fetch data is a common pattern. However, if you define a function inside useEffect (like fetchData), it will be recreated every time the component re-renders. This can cause issues when that function is included in the dependency array of useEffect, especially in Create React App projects, where you may encounter an ESLint warning about the function being re-created on every render.

The Problem

Let’s say you have a fetchData function inside useEffect that fetches data from an API. If you include fetchData in the dependency array of useEffect, it will cause the function to be recreated every time the component re-renders, even if nothing about the function has actually changed. This can lead to unnecessary re-fetching and other issues.

In Create React App, this will often result in an ESLint warning about missing dependencies or functions that change on every render.

How to Fix It with useCallback

To solve this problem, we can use the useCallback hook to memoize the fetchData function. By doing this, React will "remember" the function and only recreate it if its dependencies change.

Example: Fetching Data from an API

Before Using useCallback

Here’s the initial version of the code where fetchData is defined inside the useEffect hook:

import { useState, useEffect } from 'react';

const url = 'https://api.github.com/users';

const App = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const users = await response.json();
        setUsers(users);
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, []);  // Empty dependency array, but the fetchData function is recreated on every render

  return (
    <section>
      <h3>Github Users</h3>
      <ul className="users">
        {users.map((user) => (
          <li key={user.id}>
            <img src={user.avatar_url} alt={user.login} />
            <div>
              <h5>{user.login}</h5>
              <a href={user.html_url}>Profile</a>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this setup, the fetchData function is defined inside useEffect. Each time the component re-renders, fetchData is recreated. While this works, it can lead to issues in projects like Create React App, where you might see ESLint warnings about the fetchData function being recreated every render.

After Using useCallback

Now, let’s fix this by memoizing the fetchData function using useCallback:

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

const url = 'https://api.github.com/users';

const App = () => {
  const [users, setUsers] = useState([]);

  // Use useCallback to memoize the fetchData function
  const fetchData = useCallback(async () => {
    try {
      const response = await fetch(url);
      const users = await response.json();
      setUsers(users);
    } catch (error) {
      console.log(error);
    }
  }, []);  // Empty dependency array: fetchData is only created once on initial render

  useEffect(() => {
    fetchData();  // Call the memoized fetchData function
  }, [fetchData]);  // Dependency array ensures fetchData is called only when it changes

  return (
    <section>
      <h3>Github Users</h3>
      <ul className="users">
        {users.map((user) => (
          <li key={user.id}>
            <img src={user.avatar_url} alt={user.login} />
            <div>
              <h5>{user.login}</h5>
              <a href={user.html_url}>Profile</a>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useCallback: The fetchData function is now wrapped in the useCallback hook. This ensures that the function is only recreated if its dependencies change. Since we’ve passed an empty dependency array ([]), the function will be created only once, when the component first renders.
  • fetchData in useEffect: The memoized fetchData is passed to useEffect, and fetchData is added to the dependency array. This ensures that useEffect is called whenever the function changes, but since it’s only created once, this prevents unnecessary re-fetching.

Why Use useCallback Here?

  • Avoid unnecessary re-creations of the function: Without useCallback, the fetchData function would be recreated on every render, which could trigger unnecessary re-fetching.
  • Prevent ESLint warnings: In Create React App, if a function is defined inside useEffect and is not included in the dependency array, you’ll get an ESLint warning. Using useCallback fixes this issue and ensures the function is stable across renders.
  • Better performance: Memoizing the function ensures that it’s only recreated when necessary, improving the performance of your app.

Conclusion

By using the useCallback hook, we ensure that functions inside useEffect are only recreated when necessary. This not only prevents unnecessary re-renders and re-fetching but also helps avoid warnings in Create React App projects. This makes your app more efficient and prevents unnecessary computations.