Overview
ThewithInit extension allows you to define a dynamically computed initial value for an atom. While you can typically use an init callback in the atom’s first argument (atom(() => new Date())), withInit is useful when you need to add an initial callback after atom creation or compose multiple initialization steps.
Type Signature
Parameters
State | (state, ...params) => State
required
The initial value or a function that returns the initial value based on current state.As value: Direct initial state
As function: Receives current state and any init params, returns new initial state
As function: Receives current state and any init params, returns new initial state
Return Value
Returns an extension that sets the initial state on first evaluation.Examples
Basic Init Value
Init with Callback
Compose Initial State
Conditional Init
Multiple Init Extensions
Different Contexts
Reusable Init Extension
Init with Parameters
Cycle Breaking
withInitHook
Runs a callback during initialization without modifying the state:Init Hook with Queue
isInit Helper
Checks if currently in the initialization phase:Use Cases
Random ID Generation
Timestamp Creation
Load from LocalStorage
Merge Default Config
Environment-Specific Initialization
Feature Flag Init
Sequential Initialization
Analytics on Init
Related
- atom - Base atom primitive
- withComputed - Add computed behavior
- withChangeHook - React to state changes