1

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?

2
  • 1
    You can maintain a single function instance with the useCallback hook Commented May 5, 2022 at 22:10
  • That's just how closures (functions defined inside functions) work. Why react chose to use this style is not known. Commented May 5, 2022 at 23:04

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

The syntax used for useCallback calls still re-creates the function object every time, it just doesn't return the new function from useCallback when the memoisation dependencies didn't change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.