Proper state initialization in React improves performance and prevents bugs. Here's how to do it effectively.
Basic Initialization#
Lazy Initialization#
Props to State (Anti-pattern Warning)#
Derived State#
Complex State Objects#
useReducer for Complex State#
Ref for Non-Render Values#
State Lifting#
Initial State from URL#
Reset State Pattern#
Best Practices#
Initialization:
✓ Use lazy init for expensive ops
✓ Provide complete initial shape
✓ Use functions for localStorage
✓ Consider useReducer for complex
Performance:
✓ Compute derived values, don't store
✓ Use refs for non-render values
✓ useMemo for expensive derivations
✓ Split state by update frequency
Patterns:
✓ Lift state to common ancestor
✓ Use key to reset components
✓ Sync URL with state when needed
✓ Reset state explicitly when needed
Avoid:
✗ Mirroring props in state
✗ Storing derived state
✗ Expensive inline initialization
✗ Unnecessary state synchronization
Conclusion#
Proper state initialization improves performance and prevents bugs. Use lazy initialization for expensive computations, compute derived values during render instead of storing them, and use refs for values that don't affect rendering. Lift state to the appropriate level and use the key prop to reset components when needed.