Container Components vs Presentational Components :👈 👉:How to Organize API Calls in a React Application

When to Use Context vs a State Management Library

1. Introduction

In React applications, components often need to share data. For example:

  • User authentication information
  • Theme settings (Light Mode / Dark Mode)
  • Shopping cart details
  • Notifications
  • User preferences
  • Application-wide settings

For sharing data between components, React provides the Context API. For more complex state management, developers can use libraries such as Redux Toolkit, Zustand and MobX.

The important question is:

When is React Context sufficient, and when should you introduce a state management library?

2. What Is React Context?

React Context allows you to share data across multiple components without passing props manually through every intermediate component.

Normally, data is passed from parent to child using props. When deeply nested components need the same data, this can lead to prop drilling.

Example: Without Context (Prop Drilling)

function App() {
  const user = {
    name: "John",
    role: "Admin"
  };
  return <Dashboard user={user} />;
}
function Dashboard({ user }) {
  return <Profile user={user} />;
}
function Profile({ user }) {
  return <UserDetails user={user} />;
}
function UserDetails({ user }) {
  return <h2>Welcome {user.name}</h2>;
}

Here, the user object is passed through multiple components, even though only UserDetails needs it.

Example: With React Context

import { createContext, useContext } from "react";
const UserContext = createContext(null);
function App() {
  const user = {
    name: "John",
    role: "Admin"
  };
  return (
    <UserContext.Provider value={user}>
      <Dashboard />
    </UserContext.Provider>
  );
}
function Dashboard() {
  return <Profile />;
}
function Profile() {
  return <UserDetails />;
}
function UserDetails() {
  const user = useContext(UserContext);
  return <h2>Welcome {user.name}</h2>;
}

Now, UserDetails accesses the user information directly using useContext, without intermediate components passing props.

Note: In React 19, you can also use <UserContext value={user}> instead of <UserContext.Provider value={user}>. The Provider syntax remains common in React 18 and earlier.

3. When Should You Use React Context?

Context is suitable when you need to share relatively simple application-wide or feature-wide data.

3.1 Authentication Information

Share information such as:

  • Current logged-in user
  • User role
  • Authentication status
const AuthContext = createContext(null);
function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  return (
    <AuthContext.Provider value={{ user, setUser }}>
      {children}
    </AuthContext.Provider>
  );
}
function UserProfile() {
  const { user } = useContext(AuthContext);
  if (!user) {
    return <p>Please log in</p>;
  }
  return <h2>Welcome {user.name}</h2>;
}

3.2 Theme Management

Share the selected application theme across components.

const ThemeContext = createContext(null);
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  function toggleTheme() {
    setTheme(current =>
      current === "light" ? "dark" : "light"
    );
  }
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}
function ThemeButton() {
  const { theme, toggleTheme } = useContext(ThemeContext);
  return (
    <button onClick={toggleTheme}>
      Current Theme: {theme}
    </button>
  );
}

3.3 Language and Localization

Share the selected language across different parts of the application.

For example, changing the language from English to Kannada should update text in the navigation, dashboard and other components.

3.4 Application Settings

Context can be used for relatively simple shared settings such as:

  • Display preferences
  • Selected language
  • Application configuration
  • Accessibility preferences

4. Limitations of React Context

Context is useful, but it is not a complete replacement for every state management solution.

4.1 Re-rendering of Context Consumers

When a Context provider receives a different value, components consuming that Context are scheduled to render again.

const AppContext = createContext(null);
function AppProvider({ children }) {
  const [count, setCount] = useState(0);
  const [theme, setTheme] = useState("light");
  const value = {
    count,
    setCount,
    theme,
    setTheme
  };
  return (
    <AppContext.Provider value={value}>
      {children}
    </AppContext.Provider>
  );
}

Suppose one component only needs theme, while another only needs count.

When count changes, the provider value changes. Components consuming this Context may render again even if they only use theme.

This can become a performance concern when a large application places frequently changing, unrelated state inside one Context.

4.2 No Built-in Selectors for Individual State Fields

React Context does not provide a built-in selector mechanism that allows a component to subscribe only to a particular field of a Context value.

For example, a component consuming a Context containing 20 properties is subscribed to that Context value, not just one property.

4.3 Complex State Logic Becomes Difficult to Maintain

When an application contains:

  • Many related state updates
  • Complex business workflows
  • Undo and redo requirements
  • Multiple components updating shared state
  • Advanced debugging requirements

Managing everything through multiple Context providers and state setters can become difficult.

4.4 No Built-in Advanced State Management Tools

Context does not provide a complete built-in solution for:

  • State selectors and fine-grained subscriptions
  • Redux-style action history and DevTools workflows
  • Undo and redo functionality
  • Middleware-based workflows
  • Complex server-state caching and synchronization

These capabilities may be available through additional libraries or application-specific implementations.

5. What Is a State Management Library?

A state management library provides additional tools and patterns for managing shared application state.

Popular React state management libraries include:

  • Redux Toolkit
  • Zustand
  • MobX

These libraries offer different approaches to organizing, updating and subscribing to shared state.

6. Popular State Management Libraries

6.1 Redux Toolkit

Redux Toolkit is the recommended standard approach for writing Redux logic.

It provides a structured way to manage application state through a central store, reducers and actions.

Useful features include:

  • Centralized state management
  • Predictable state updates
  • Reducers and actions
  • Middleware support
  • Redux DevTools integration
  • Selectors for reading specific state

Example:

import { createSlice, configureStore } from "@reduxjs/toolkit";
const counterSlice = createSlice({
  name: "counter",
  initialState: {
    count: 0
  },
  reducers: {
    increment: state => {
      state.count += 1;
    },
    decrement: state => {
      state.count -= 1;
    }
  }
});
const store = configureStore({
  reducer: {
    counter: counterSlice.reducer
  }
});
export const { increment, decrement } = counterSlice.actions;

Component usage:

import { useSelector, useDispatch } from "react-redux";
import { increment } from "./store";
function Counter() {
  const count = useSelector(state => state.counter.count);
  const dispatch = useDispatch();
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => dispatch(increment())}>
        Increment
      </button>
    </div>
  );
}

When to use Redux Toolkit:

  • Large applications with complex shared state.
  • Many components need to update and access the same state.
  • Predictable state transitions are important.
  • You need structured debugging and middleware.
  • Multiple developers work on a large application.

6.2 Zustand

Zustand is a lightweight state management library with a simple API.

It allows components to access shared state without wrapping the application in multiple Context providers.

Useful features include:

  • Simple store creation
  • Minimal boilerplate
  • Selector-based subscriptions
  • Good TypeScript support
  • Optional middleware and persistence integrations

Example:

import { create } from "zustand";
const useCounterStore = create(set => ({
  count: 0,
  increment: () =>
    set(state => ({
      count: state.count + 1
    }))
}));
function Counter() {
  const count = useCounterStore(state => state.count);
  const increment = useCounterStore(state => state.increment);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increment}>
        Increment
      </button>
    </div>
  );
}

When to use Zustand:

  • You need shared state without much boilerplate.
  • Several components need access to the same state.
  • You want selector-based subscriptions.
  • You prefer a lightweight alternative to Redux Toolkit.

6.3 MobX

MobX is a state management library based on observable state and reactive updates.

It tracks which observable values components use and updates observers when those values change.

Useful features include:

  • Observable state
  • Reactive updates
  • Computed values
  • Actions for modifying state
  • Less manual subscription management

Example:

import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react-lite";
class CounterStore {
  count = 0;
  constructor() {
    makeAutoObservable(this);
  }
  increment() {
    this.count++;
  }
}
const counterStore = new CounterStore();
const Counter = observer(() => {
  return (
    <div>
      <h2>Count: {counterStore.count}</h2>
      <button onClick={() => counterStore.increment()}>
        Increment
      </button>
    </div>
  );
});

When to use MobX:

  • You prefer observable and reactive state.
  • Your application has complex interconnected state.
  • You want computed values that update automatically.
  • Your team is comfortable with MobX's reactive programming model.

7. Context vs Redux Toolkit vs Zustand vs MobX

Feature Context API Redux Toolkit Zustand MobX
Type Built-in React API State management library State management library State management library
Setup Simple More structured setup Very simple Moderate
Boilerplate Low to moderate Moderate Low Low to moderate
State subscriptions Context-level updates Selector-based Selector-based Observable dependency tracking
Debugging React DevTools Redux DevTools Optional DevTools middleware MobX DevTools ecosystem
Middleware Not built in Supported Optional middleware Different reactive mechanisms
Best suited for Simple shared values Complex, structured shared state Lightweight shared state Reactive observable state

8. Context vs State Management Library: Practical Decision Guide

Use the following guidelines when choosing an approach.

Scenario 1: Theme Management

Requirement: Share the selected light or dark theme across the application.

Recommended: React Context.

Reason: Theme information is relatively simple and does not usually require a complex state management library.

Scenario 2: Authentication Information

Requirement: Share the logged-in user, authentication status and user role.

Recommended: Context or a state management library, depending on complexity.

Reason: Context is sufficient for simple authentication UI state. Larger applications may benefit from a more structured state solution. Authentication and authorization must still be enforced securely by the server.

Scenario 3: Shopping Cart

Requirement: Manage products, quantities, discounts, totals and cart updates across multiple components.

Recommended: Zustand or Redux Toolkit when the cart logic and sharing requirements become complex.

Reason: Multiple components may update and read cart information, and selector-based subscriptions can be useful.

Scenario 4: Large Enterprise Application

Requirement: Multiple features share complex state, with many update operations and debugging requirements.

Recommended: Redux Toolkit or another suitable state management library.

Reason: Structured updates, centralized state and debugging tools can help manage complexity.

Scenario 5: Small Application

Requirement: Share a few settings and simple user preferences.

Recommended: React Context or local component state.

Reason: Introducing a state management library may add unnecessary complexity.

9. Important: Server State vs Client State

One common architectural mistake is treating all application data as the same type of state.

In React applications, it is useful to distinguish between two categories.

Client State

Client state represents information managed by the frontend application.

Examples:

  • Selected theme
  • Open or closed modal
  • Selected tab
  • Shopping cart UI state
  • Form input values

Suitable solutions include:

  • useState
  • useReducer
  • Context API
  • Zustand
  • Redux Toolkit

Server State

Server state represents data fetched from an external server or API.

Examples:

  • Customer details
  • Product lists
  • Order history
  • Transaction information
  • Dashboard reports

Server state has additional concerns:

  • Loading and error handling
  • Caching
  • Background refetching
  • Request cancellation
  • Data synchronization
  • Stale data management

Libraries such as TanStack Query and RTK Query are designed to help manage server state.

Example using TanStack Query:

import { useQuery } from "@tanstack/react-query";
function Users() {
  const { data, isLoading, error } = useQuery({
    queryKey: ["users"],
    queryFn: async () => {
      const response = await fetch("/api/users");
      if (!response.ok) {
        throw new Error("Failed to fetch users");
      }
      return response.json();
    }
  });
  if (isLoading) {
    return <p>Loading...</p>;
  }
  if (error) {
    return <p>Unable to load users</p>;
  }
  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

TanStack Query manages the server-data lifecycle, including caching and refetching. It does not replace all client-state management.

10. Common Mistakes to Avoid

  1. Using Context for everything: Not every state value needs to be globally shared.
  2. Using Redux for every small application: Avoid introducing unnecessary complexity.
  3. Putting unrelated state in one Context: Separate contexts based on responsibility and update frequency when useful.
  4. Ignoring re-renders: Frequently changing Context values can cause unnecessary work in consuming components.
  5. Confusing server state with client state: API caching and synchronization often need dedicated tools.
  6. Choosing a library only because it is popular: Select tools based on actual application requirements.
  7. Duplicating the same data in multiple stores: Avoid creating synchronization problems.
  8. Making everything global: Keep state local when only one component or a small component section needs it.

11. Recommended Architecture for a React Application

A practical application can use different state management approaches for different responsibilities.

React Application
│
├── Local Component State
│   ├── Form inputs
│   ├── Modal visibility
│   └── Selected tabs
│
├── React Context
│   ├── Theme
│   ├── Language
│   └── Simple authentication UI state
│
├── Zustand / Redux Toolkit
│   ├── Complex shopping cart state
│   ├── Shared workflow state
│   └── Complex client-side business state
│
└── TanStack Query / RTK Query
    ├── Customer API data
    ├── Product API data
    └── Order API data

This is an example architecture, not a requirement to use all these libraries together.

12. Decision Checklist

Requirement Recommended Solution
State used by one component useState
Complex state transitions within one component useReducer
Simple shared application settings Context API
Complex shared client state Redux Toolkit or Zustand
Observable reactive state MobX
API caching and synchronization TanStack Query or RTK Query
Shared state with structured actions and debugging requirements Redux Toolkit

13. Common Interview Questions

Q1. What is the difference between Context API and Redux?

Context is a built-in React feature for sharing values across components. Redux Toolkit is a state management solution that provides a structured store, actions, reducers, middleware and debugging tools.

Q2. Can Context replace Redux?

For simple shared state, Context may be sufficient. For complex shared state, advanced debugging, middleware and structured state updates, Redux Toolkit may be more suitable.

Q3. Does Context cause unnecessary re-renders?

When a provider value changes, components consuming that Context are scheduled to render again. Splitting unrelated contexts, stabilizing provider values where appropriate and keeping frequently changing state local can help.

Q4. Is Zustand better than Redux?

Neither is universally better. Zustand is simpler and lightweight, while Redux Toolkit offers a more structured approach and a mature debugging ecosystem. Choose based on application requirements.

Q5. Should API responses be stored in Context?

Small amounts of shared API data can be stored in Context, but applications with caching, refetching and synchronization requirements often benefit from TanStack Query or RTK Query.

Q6. What is the difference between client state and server state?

Client state is managed by the frontend, such as selected tabs and modal visibility. Server state comes from external APIs and requires caching, synchronization and refetching considerations.

Q7. Can we use Context and Redux together?

Yes. They can coexist, although using multiple state solutions should have a clear purpose to avoid unnecessary complexity and duplicated state.

Q8. When should we introduce a state management library?

When shared state becomes complex, many components need to update it, state transitions become difficult to maintain, or the application needs more advanced debugging and subscription capabilities.

14. Final Takeaway

Use Context when:

  • You need to share simple application-wide values.
  • You want to avoid prop drilling.
  • Your state updates are relatively straightforward.

Use a State Management Library when:

  • You have complex shared client state.
  • Many components need independent subscriptions to shared data.
  • You need structured updates and advanced debugging.
  • Your application has complicated state transitions.

Use TanStack Query or RTK Query when:

  • You need to manage API data, caching, refetching and synchronization.

Most important principle: Start with local React state. Introduce Context or a state management library only when the application's actual requirements justify it. Do not make every piece of state global.

🔙
Container Components vs Presentational Components :👈 👉:How to Organize API Calls in a React Application

Comments and Discussion