How to Handle Effects Using Hooks in React with TypeScript

There are 2 hooks to handle side-effects in React:

The first one fires after layout and paint, during a deferred event. The second one works synchronously before the next paint, and used to handle effects that are visible to a user.


The useEffect hook accepts 2 arguments:

  • a side-effect function,

  • and an array of dependencies that make the effect fire.

By default, useEffect fires on every re-render. If you need it to fire only when certain values change use the second argument to point out those values.

You can also return from an effect a clean-up function. The clean-up function runs before the component is removed from the UI to prevent memory leaks.

You don't need any additional typings for the useEffect hook. However, TypeScript knows about its inner structure and type signatures, so there is no chance to compile something like: