How to Use useCallback Hook with TypeScript

The useCallback hook returns a memoized callback that only changes if one of the dependencies has changed. This helps us to avoid unwanted and unnecessary components re-renders.

Basic Syntax#

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 EmailInput.

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 InputEmail and 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.