In React, a function declared inside a component gets re-created on every render with a different reference, causing issues with useEffect and child components. A useEffect dependent on this function will execute again on each render. Similarly, child components will re-render unnecessarily. To prevent this, we can use React.memo to cache the child component and ensure it only re-renders if its props change. However, when passing functions as props, the child component will still re-render even if its props don't change. This is because the function reference changes on each render, causing the child component to re-render. To fix this, we can use the useCallback hook to cache the function's reference across renders. useCallback takes a function and an array of dependencies as arguments, and returns a cached function that only changes when the dependencies change. By using useCallback, we can ensure that the function has a stable reference and prevent unnecessary re-renders. We should use useCallback when we have event handlers, functions called inside useEffect, or custom hooks that return functions.
dev.to
dev.to
