When to Use useCallback in React

most React developers use useCallback wrong. not because they don't understand it. because they were taught the wrong rule. the rule they heard: "wrap functions in useCallback to prevent unnecessary re-renders. the actual rule: useCallback only helps when you pass that function to a child component wrapped in React.memo or as a dependency in useEffect. that's it. useCallback doesn't prevent re-renders of the parent. it just memoizes the function reference so children don't see a "new" function every render. three questions to ask before reaching for useCallback: - is this function passed to a memoized child component? - is this function a dependency in a useEffect? - is this function expensive to recreate? if none of these just write the function normally. the best optimisation is usually the one you don't add. #reactjs #typescript #webdevelopment #buildinpublic #javascript

  • No alternative text description for this image

That’s a great point. When I started, I was also somewhat confused about when I should use it. I think this happens because most of us learn how to use React, but things only become clear once we understand how it works under the hood.

To view or add a comment, sign in

Explore content categories