April 7, 2024

State management in React

State management in React refers to how you store, update, and share data across components in a React application. Managing state effectively is crucial for building responsive, maintainable apps β€” especially as your app grows.


🧠 What is State in React?

In React, state is data that determines how your UI behaves. When state changes, the UI updates.

There are two main types of state:

TypeDescription
Local stateState owned by a single component (useState)
Global stateShared across multiple components (via Context, Redux, etc.)

πŸ”Ή 1. Local State Management

Use React Hooks like useState and useReducer to manage local state.

const [count, setCount] = useState(0);

For more complex logic:

const [state, dispatch] = useReducer(reducerFunction, initialState);

πŸ”Ή 2. Global State Management

Used when you need to share state between many components. Options include:

βœ… React Context API

  • Built-in solution
  • Works well for simple global data (like theme, user info, etc.)
const UserContext = React.createContext();

<UserContext.Provider value={user}>
  <Child />
</UserContext.Provider>

Access it with useContext(UserContext).


βœ… Third-party Libraries

LibraryWhen to Use
ReduxFor large apps with complex global state, actions, reducers
ZustandSimpler alternative to Redux, minimal and fast
RecoilBuilt by Facebook, supports atom-based state model
MobXObservable state, automatic tracking of dependencies
JotaiPrimitive and modern global state library
XStateBased on state machines, for apps with well-defined transitions

πŸ”Έ 3. Derived State

Sometimes you calculate state based on other state or props.

Use:

const filteredItems = items.filter(item => item.active);

Or memoize for performance:

const filteredItems = useMemo(() => {
  return items.filter(item => item.active);
}, [items]);

πŸ”Έ 4. Server State

State that comes from a server (e.g., API data). Managed via:

  • useEffect + fetch or axios
  • React Query, SWR, Apollo Client for powerful caching, revalidation, pagination, etc.

πŸ”Έ 5. URL State

URL-related data (like query parameters, pathname) is also state.

Managed via:

  • react-router-dom
  • useSearchParams, useLocation, useNavigate

🧩 Summary Table

TypeTools/Methods
Local stateuseState, useReducer
Global stateContext API, Redux, Zustand, etc.
Derived stateuseMemo, inline calculations
Server stateReact Query, Axios + useEffect
URL stateReact Router

πŸ” Tips for Effective State Management

  • Keep state close to where it’s needed
  • Don’t overuse global state
  • Use useReducer for complex updates
  • Prefer libraries (like React Query) for server state
  • Don’t store derived data in state β€” compute it when needed