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?
CodePudding user response:
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