The basic syntax for the
useCallback hook is:
You don't need any additional typings since TypeScript knows that
useCallback accepts a function and an array of dependencies.
It is preferable to use
eslint-plugin-react-hooks though, to ensure you don't miss any argument in the dependencies array but that's optional.
Using with Components#
Let's assume we have a login form component:
And then we have 2 input components:
The problem is that when we change an email React will re-render both inputs instead of only
This is happening because handler functions are being created on every re-render of the
LoginForm component. So, on each render there are new handler functions for the
PasswordEmail component, that's why they re-render each time. Let's fix that!
Now, when we change an email or a password only the corresponding input component re-renders.