'Why does react/javascript recreates a function instance every time we call it?

For example, onChange function:

const MyComponent = () => {
  const onChange = (e) => {
    doSomething(e.target.value)
  }

  return <input onChange={onChange} />
};

gets recreated on every change. Why is that, why can not the function keep the original reference?



Solution 1:[1]

React function components are just functions that run every render cycle and return JSX. So every render there's a completely different onChange constant that holds a different reference to the function(even though the behavior is the same).

If you want to keep the reference between renders, you should use React.useCallback. You can find more about it in React docs: https://reactjs.org/docs/hooks-reference.html#usecallback

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bergi