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