Side Effects

Essential React

useEffect

What is it good for?

Valid use cases

  • Subscribing to events (window, ...)
  • Releasing resources to prevent a memory leak
  • Cancelling a network request/asynchronous operation
Duplicate evaluation

What's going on here?

index.tsx

In development, when using Strict Mode , components are remounted: mount, unmount, mount.

Purpose: future-proofing the app.

Purpose: future-proofing the app

  • Effects are executed at least twice in development
    (not in production)
  • If your code with useEffect doesn't behave as desired, you should follow up on a different approach

Cleanup is necessary for...

  • Unsubscribing from a pub-sub interface
  • Releasing resources to prevent a memory leak
  • Cancelling a network request/asynchronous operation

useEffect as last-resort

  • Don't use useEffect to update state based on props or state, whenever possible calculate all dependent states on the fly
    (if the calculation is expensive, use the useMemo Hook)
  • Don't invoke callbacks on state change, whenever possible invoke callbacks as part of event handling logic

Custom Hooks

We can reuse a concrete Hook logic by extracting it into a
custom Hook.

The logic to be extracted can use a single or multiple Hooks.

We simply move the logic into its own function.

In the component we then call this function.

Stick to the Hooks naming convention: use*

Exercise

  • Using useEffect, listen on the profile form for the window paste event and set the pasted text to the forms name field
  • Extract the newly created logic to a custom Hook
  • Using useEffect, listen on the profile form for the window paste event and set the pasted text to the forms name field
  • Extract the newly created logic to a custom Hook

Solution

useWindowPaste.ts

Profile.tsx

Recap

We learned…

  • How to use the useEffect Hook
  • When to use useEffect and when to use a different approach to reach your goal
  • How to cleanup side effects in useEffect
  • How to extract Hook logic from components into Custom Hooks

Questions?