0

Sorry if this is a stupid question, I'm new to JavaScript and React. UseCallback is needed to wrap a callback function to avoid recreating the function because it is defined in a functional component which is re-run each time it's state changes. Why don't we just define the callback outside of the functional component to avoid this problem?

// define handleClick here instead?
// const handleClick ...

function MyComponent() {
  // handleClick is re-created on each render
  const handleClick = () => { console.log('Clicked!'); };
}

1 Answers1

5

If the function is defined outside the component, it can't use the useful dynamic values that would otherwise be easily referenceable inside the component. Most importantly, state and props - the outside function won't have scope of the identifiers defined inside.

If the function doesn't need any such dynamic values - for a silly example:

function alertError() {
  alert('There was an error');
}

then defining it outside the component is perfectly fine (and preferable to the unnecessary complication of useCallback)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320