One of the things that has often tripped me up with React and hooks is the order in which stuff happens. I recently came across the following react hook flow diagram, which I think neatly summarises the flow of hooks:
Not everything about it was immediately obvious, so here are my notes on how to interpret the diagram.
Breakdown of the hook flow diagram
- a component can be in one of three distinct lifecycle phases (mount, update, unmount), represented by the columns in the diagram
- when in any given phase, the order in which the action are processed are indicated by the down-facing arrows. for example, react updated the DOM before running layout effects
- the actions (e.g. 'render', run effect', 'cleanup effects', etc.) can occur in one or more of these phases. they are represented by the rows (they span the whole row, but are marked within a specific column). for example, a component renders when it first mounts, but also when it updates
- the background colour of the rows indicates whether a specific action happens during a given lifecycle phase. a faded background colour implies not, and a non-faded implies yes. for example, a component does not render when it unmounts