2023-08-03 - React Frontend useEffect notes

From Izara Wiki
Jump to navigation Jump to search

When does useEffect trigger

useEffect triggers at different times:

  1. No dependency list
    • invokes on every render
  2. Empty dependency list
    • triggers when component mounts
  3. dependency list is array of states
    • triggers whenever any states in the dependency list change (same as triggering a new render)
    • will also trigger once when component mounts with states set to default values (or current values for state sent in from parent components)

When does clean up function trigger

Return function from useEffect is called a cleanup function, this triggers at different times:

  1. No dependency list
    • assume each render will invoke cleanup for previous useEffect invocation
  2. Empty dependency list
    • triggers when component dismounts
    • good for logic that persists the life of the component and needs to be cleaned up
  3. dependency list is array of states
    • each time a state in the dependency list changes will invoke cleanup for previous useEffect invocation

Dependency list

If want to reference state inside useEffect it should be in the dependency list, but this will also trigger cleanup and a new invocation each time any of the listed states change. There are ways to solve this, see references.

Cancelling asynchronous requests if component dismounts

If we navigate away from a component (it dismounts) with pending async code, React throws a warning:

// Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

Apparently it is not serious but there are ways to solve this, eg abort controller, see references.

Setting state of both parent state and current component state

Not sure: had error about changing state of a component while another was rendering when setting parent and current component state inside useEffect, not sure if this was the cause of the error but could be fixed by moving all state to be parent state, or ?only updating current states.

Idea was to update state in two useEffects one for current component state which triggers a second useEffect that updates parent states - not tested yet

References