What is State Management?
-
State refers to data that determines what the UI looks like.
-
State management means organizing, updating, and sharing that data across components.
Types of State
| Type | Description | Scope |
|---|---|---|
| Local State | State inside a single component (e.g., form inputs) | Component only |
| Global State | Shared across many components (e.g., user auth) | Entire app or large parts |
| Server State | Data fetched from a backend or API | App-wide or page-wide |
| URL State | Data in the URL query params or path | Across pages or routes |
Managing State Locally
-
Use React hooks like
useStateanduseReducer.
Example:
Managing Global State
1. React Context API
-
Built-in way to share state without prop drilling.
-
Good for light global state like themes or user info.
Example:
2. State Management Libraries
-
Redux: Popular and powerful, supports complex global state.
-
Recoil: Simplifies shared state with atoms and selectors.
-
Zustand, MobX, Jotai: Other lighter alternatives.
Managing Server State
-
Use libraries like React Query, SWR for caching and syncing remote data.
-
Example: SWR
Summary Table
| State Type | Management Method | When to Use |
|---|---|---|
| Local State | useState, useReducer |
Component-specific data |
| Global State | Context API, Redux, Recoil | Shared data across app |
| Server State | React Query, SWR | Fetching/caching remote data |
| URL State | Next.js router query params | Syncing UI with URL |
