Ankit KanojiyaAdvanced

Evergreen guide by Ankit Kanojiya · Advanced · Frontend

Managing State in Modern React: Local, Context, and Server State

A framework for choosing where state should live: component-local, shared via context, or synchronized from a server. Explains why server state needs different tools than client state.

State management questions usually get answered with a library name, but the more useful question is what kind of state is being managed. Different categories of state have different lifecycles and ownership, and matching each to the right mechanism prevents most of the complexity people blame on React. A clear mental model matters more than any single tool.

Categories of state

It helps to separate state into a few kinds:

  • Local UI state: the open or closed status of a menu, a form field value, a hover flag. Owned by one component.
  • Shared client state: a theme, the current user's preferences, a selected locale. Needed by many components but originates on the client.
  • Server state: data that lives in a database and is fetched over the network, such as a list of posts or a user profile. The client holds a cached copy, not the source of truth.
  • URL state: filters, pagination, and the current view, which often belong in the address bar so they can be shared and restored.

Most pain comes from treating server state like client state. They behave differently and need different tools.

Local state with useState and useReducer

Keep state as close to where it is used as possible. Co-locating state limits re-renders and keeps components easy to reason about.

function Disclosure() {
  const [open, setOpen] = useState(false);
  return (
    <section>
      <button onClick={() => setOpen((o) => !o)}>Toggle</button>
      {open && <p>Details here</p>}
    </section>
  );
}

When updates follow rules or several values change together, useReducer keeps the logic in one predictable place:

function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'reset': return { count: 0 };
    default: return state;
  }
}

Reach for a reducer when transitions become hard to express as isolated setState calls.

Context for shared client state

Context passes values down the tree without threading props through every level. It solves distribution, not performance.

const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Page />
    </ThemeContext.Provider>
  );
}

Two cautions:

  • Every consumer re-renders when the context value changes. A single context holding many unrelated values causes broad re-renders. Split contexts by concern, or memoize the provider value.
  • Context is not a cache or a state manager. It is a transport. Putting server data directly into context tends to reinvent caching, poorly.

Server state deserves its own tools

Server state is fundamentally different from client state:

  • It is asynchronous and can fail.
  • It can be stale, because the real value lives on the server and may change without the client knowing.
  • It is shared across components that should not each fetch it independently.
  • It needs loading, error, retry, and revalidation behavior.

Trying to model this with useState and manual useEffect fetching leads to duplicated requests, race conditions, and stale data. Dedicated data libraries such as React Query or SWR handle caching, deduplication, background refetching, and invalidation.

function Profile({ id }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', id],
    queryFn: () => fetch('/api/users/' + id).then((r) => r.json()),
  });

  if (isLoading) return 'Loading';
  if (error) return 'Something went wrong';
  return data.name;
}

The cache key ties the request to its data, so multiple components asking for the same user share one request and one cached result.

URL as state

For things like the active tab, search query, or page number, the URL is often the best store. It makes the view shareable, restorable on refresh, and navigable with the back button. Pushing this state into client memory loses all of those properties.

A decision guide

  • Used by one component only: local useState or useReducer.
  • Shared by many components, originates on the client, changes rarely: context.
  • Comes from the server and is cached on the client: a data-fetching library, not context or global state.
  • Should be shareable or survive a refresh: the URL.
  • Complex client state shared widely across a large app: a dedicated client store, chosen only after the simpler options prove insufficient.

Avoiding common mistakes

  • Do not lift state higher than it needs to go. Co-location reduces re-renders and coupling.
  • Do not store derived values in state. Compute them during render instead, to avoid them going out of sync.
  • Do not put server data in context and then rebuild caching by hand.
  • Introduce a global store only when prop drilling and context genuinely stop scaling.

Choosing the right category first makes the tool choice almost obvious, and keeps most of the app on the simplest option that works.