The State Initializer Pattern, explained by Kent C. Dodds
This one is Kent's, and his write-up is the one to read:
The State Initializer Pattern by Kent C. Dodds
Image by Silvio Kundt
The part I reach for most
The pattern lets whoever uses your component or hook decide what its initial
state is, and then reset back to exactly that later — which is how
downshift and ReachUI let you
clear a dropdown without losing the defaults you configured.
The detail that makes it work is that the initial value has to be captured
once, not read again on every render. Otherwise reset sends the component
back to whatever the prop happens to be right now, rather than what it started
as:
const { current: initialState } = React.useRef({ count: initialCount })
Kent's post walks through the alternatives, when each is worth it, and how this
relates to resetting a component with the key prop instead — which I have a
separate note about.
Since the original is already in English, republishing it here would only compete with it. What I have done instead is translate it into Spanish — a language it was not available in — with attribution and a link back to the original.