How to Avoid Prop Drilling :👈 👉:How to Design Error Boundaries

How to Manage State Across Multiple Pages

How to Manage State Across Multiple Pages in React

1. What Does State Across Multiple Pages Mean?

In React, state represents data that a component needs to remember and use.

When an application has multiple pages, you may need to share the same data between different pages.

For example, consider an e-commerce application:

  • Home Page: Displays products.
  • Product Details Page: Displays information about a selected product.
  • Cart Page: Displays products added to the cart.
  • Checkout Page: Displays the order details.

If a user adds a product to the cart on the Product Details page, that product should still be available when the user navigates to the Cart page.

This is called managing state across multiple pages.

2. Different Types of State in React

Before selecting a state management approach, understand the different types of state.

State TypeDescriptionExample
Local StateUsed within a componentDropdown open/closed
Shared StateUsed by multiple components or pagesShopping cart
Global StateShared across many parts of the applicationUser authentication
URL StateStored in the URLSearch term, page number, filters
Server StateData fetched from an APIProduct list, user profile
Persistent StateData that should survive a page refreshTheme preference, cart data

Not every piece of state should be global. Choose the approach based on how and where the data is used.

3. Approach 1: Passing State Through Props

The simplest approach is to pass data from a parent component to its child components using props.

Example:

function App() {
  const [user, setUser] = useState({
    name: "John",
    email: "john@example.com"
  });
  return <Dashboard user={user} />;
}
function Dashboard({ user }) {
  return <UserProfile user={user} />;
}
function UserProfile({ user }) {
  return <h2>Welcome {user.name}</h2>;
}

Advantages:

  • Simple and easy to understand.
  • No additional libraries required.
  • Makes data flow explicit.

Disadvantages:

  • Data must be passed through intermediate components.
  • Can become difficult when many components need the same data.

When to use: Use props when data is shared between a parent and a small number of child components.

4. Approach 2: React Context API

React Context allows components to access shared data without manually passing props through every intermediate component.

It is useful for sharing state across multiple pages.

Example: Sharing User Information Across Pages

Step 1: Create User Context

import { createContext, useContext, useState } from "react";
const UserContext = createContext(null);
export function UserProvider({ children }) {
  const [user, setUser] = useState({
    name: "John",
    email: "john@example.com"
  });
  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
}
export function useUser() {
  return useContext(UserContext);
}

Step 2: Wrap the Application with UserProvider

import { BrowserRouter } from "react-router-dom";
import { UserProvider } from "./UserContext";
function App() {
  return (
    <UserProvider>
      <BrowserRouter>
        <AppRoutes />
      </BrowserRouter>
    </UserProvider>
  );
}

Step 3: Access User State on Different Pages

Profile Page:

import { useUser } from "./UserContext";
function ProfilePage() {
  const { user } = useUser();
  return <h2>Welcome {user.name}</h2>;
}

Settings Page:

import { useUser } from "./UserContext";
function SettingsPage() {
  const { user, setUser } = useUser();
  function updateName() {
    setUser({
      ...user,
      name: "David"
    });
  }
  return (
    <>
      <h2>{user.name}</h2>
      <button onClick={updateName}>
        Update Name
      </button>
    </>
  );
}

Now both pages access the same user state.

Advantages:

  • Built into React.
  • No additional state management library required.
  • Avoids unnecessary prop drilling.
  • Suitable for relatively simple shared state.

Disadvantages:

  • Context updates can cause consuming components to re-render.
  • Large applications may become difficult to organize if all state is placed in one Context.
  • Does not automatically provide advanced features such as request caching or persistence.

When to use: Use Context for relatively stable application-wide data such as logged-in user information, theme preferences, language preferences and application settings.

5. Approach 3: Redux Toolkit

Redux Toolkit is a popular state management solution for applications that have complex shared state.

It provides a centralized store where different pages can access and update the same data.

Example: Shopping Cart Across Multiple Pages

Step 1: Create a Cart Slice

import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
  name: "cart",
  initialState: {
    items: []
  },
  reducers: {
    addToCart: (state, action) => {
      state.items.push(action.payload);
    },
    removeFromCart: (state, action) => {
      state.items = state.items.filter(
        item => item.id !== action.payload
      );
    }
  }
});
export const { addToCart, removeFromCart } =
  cartSlice.actions;
export default cartSlice.reducer;

Step 2: Configure the Redux Store

import { configureStore } from "@reduxjs/toolkit";
import cartReducer from "./cartSlice";
export const store = configureStore({
  reducer: {
    cart: cartReducer
  }
});

Step 3: Provide the Store to the Application

import { Provider } from "react-redux";
import { store } from "./store";
function App() {
  return (
    <Provider store={store}>
      <AppRoutes />
    </Provider>
  );
}

Step 4: Add Products from the Product Page

import { useDispatch } from "react-redux";
import { addToCart } from "./cartSlice";
function ProductPage() {
  const dispatch = useDispatch();
  const product = {
    id: 1,
    name: "Laptop",
    price: 50000
  };
  return (
    <button onClick={() => dispatch(addToCart(product))}>
      Add to Cart
    </button>
  );
}

Step 5: Access Cart Data from the Cart Page

import { useSelector } from "react-redux";
function CartPage() {
  const items = useSelector(state => state.cart.items);
  return (
    <>
      <h2>Shopping Cart</h2>
      {items.map(item => (
        <p key={item.id}>
          {item.name} - ₹{item.price}
        </p>
      ))}
    </>
  );
}

The Product Page and Cart Page share the same cart state through the Redux store.

Advantages:

  • Centralized state management.
  • Suitable for complex shared state.
  • Predictable state updates.
  • Redux DevTools support.
  • Supports middleware for asynchronous operations.

Disadvantages:

  • Requires additional setup and concepts.
  • Can be unnecessary for small applications.
  • Developers need to understand slices, reducers, actions and selectors.

When to use: Use Redux Toolkit when multiple pages and components depend on complex shared state, such as shopping cart and checkout, complex user workflows, multi-step application processes, shared filters and selections, and large application-wide state.

6. Approach 4: Zustand

Zustand is a lightweight state management library. It provides a simple way to create a shared store without the Redux-style slice and reducer structure.

Example: Sharing Cart State

Step 1: Create a Store

import { create } from "zustand";
const useCartStore = create((set) => ({
  items: [],
  addToCart: (product) =>
    set((state) => ({
      items: [...state.items, product]
    })),
  removeFromCart: (id) =>
    set((state) => ({
      items: state.items.filter(item => item.id !== id)
    }))
}));
export default useCartStore;

Step 2: Update State from Product Page

import useCartStore from "./cartStore";
function ProductPage() {
  const addToCart = useCartStore(
    state => state.addToCart
  );
  const product = {
    id: 1,
    name: "Laptop",
    price: 50000
  };
  return (
    <button onClick={() => addToCart(product)}>
      Add to Cart
    </button>
  );
}

Step 3: Read State from Cart Page

import useCartStore from "./cartStore";
function CartPage() {
  const items = useCartStore(state => state.items);
  return (
    <>
      <h2>Shopping Cart</h2>
      {items.map(item => (
        <p key={item.id}>
          {item.name} - ₹{item.price}
        </p>
      ))}
    </>
  );
}

Both pages access the same Zustand store.

Advantages:

  • Simple API.
  • Less boilerplate.
  • Supports selective subscriptions.
  • Suitable for small and medium-sized shared state requirements.

Disadvantages:

  • Requires an external library.
  • Large stores still need good organization.
  • Advanced application workflows require deliberate architecture.

When to use: Use Zustand when you need simple, lightweight shared state without the additional structure of Redux Toolkit.

7. Approach 5: URL State

Some state should be stored in the URL rather than in Context or a global store.

For example:

  • Search keyword.
  • Selected category.
  • Current page number.
  • Sorting order.
  • Product ID.

URL state is particularly useful because it supports browser refresh, bookmarking and sharing links.

Example using React Router:

import { useSearchParams } from "react-router-dom";
function ProductSearchPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const search = searchParams.get("search") || "";
  function updateSearch(value) {
    setSearchParams({ search: value });
  }
  return (
    <>
      <input
        value={search}
        onChange={e => updateSearch(e.target.value)}
        placeholder="Search products"
      />
      <p>Searching for: {search}</p>
    </>
  );
}

Example URL:

/products?search=laptop

If the user refreshes the page or shares this URL, the search term remains available.

When to use: Use URL state for information that should be shareable, bookmarkable or restored through browser navigation.

8. Approach 6: Server State Using TanStack Query

Not all shared data should be stored in a global state management library.

For example, product lists, order details and customer information usually come from backend APIs.

This is called server state.

TanStack Query (React Query) helps manage server data, including:

  • Fetching API data.
  • Caching responses.
  • Refetching data.
  • Loading and error states.
  • Invalidating outdated cached data.
  • Managing mutations.

Example:

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

If another page uses the same query key and query configuration, TanStack Query can reuse its cached data according to its cache and freshness settings.

When to use: Use TanStack Query when multiple pages need data from backend APIs.

Important: TanStack Query manages server state. It is not a direct replacement for all client-side state management.

9. Comparison of State Management Approaches

ApproachBest Use CaseComplexity
PropsParent-child communicationLow
Context APISimple shared application stateLow
Redux ToolkitComplex global stateMedium
ZustandLightweight shared stateLow
URL StateSearch, filters and paginationLow
TanStack QueryAPI data and cachingMedium

10. Which Approach Should You Choose?

Consider a typical e-commerce application.

RequirementRecommended Approach
Open/close a dropdownuseState
Share logged-in user informationContext or a suitable global store
Share cart data across pagesZustand or Redux Toolkit
Store search and filter values in URLURL State
Fetch products from an APITanStack Query
Manage complex checkout workflowRedux Toolkit or Zustand
Pass data between parent and childProps

You do not need to use all these approaches in every application.

Choose the simplest approach that satisfies the requirement.

11. Important: Does Global State Survive Page Refresh?

There is an important difference between navigating between pages and refreshing the browser.

Scenario 1: Navigate Between React Pages

When using React Router, navigating between routes normally does not reload the entire application. A Context or global store placed above the routes can retain its in-memory state.

Scenario 2: Refresh the Browser

When the browser is refreshed, the JavaScript application starts again. In-memory state such as useState, Context, Redux and Zustand is normally reset.

To preserve state after refresh, use an appropriate persistence mechanism.

Examples:

  • localStorage for suitable non-sensitive preferences.
  • sessionStorage for temporary tab-specific data.
  • Backend database for important user and business data.
  • Redux Persist or Zustand persistence middleware for selected client state.

Example using Zustand persistence:

import { create } from "zustand";
import { persist } from "zustand/middleware";
const useCartStore = create(
  persist(
    (set) => ({
      items: [],
      addToCart: (product) =>
        set((state) => ({
          items: [...state.items, product]
        }))
    }),
    {
      name: "shopping-cart"
    }
  )
);

This example stores the cart in browser storage and restores it when the application starts.

Security note: Do not store passwords, access tokens or sensitive personal information in localStorage just to preserve state. Use an appropriate authentication and secure storage design.

12. Common Mistakes to Avoid

  1. Putting everything in global state: Keep component-specific data local.
  2. Using Context for every requirement: Context is not automatically the best solution for complex state.
  3. Duplicating API data unnecessarily: Consider a server-state library such as TanStack Query.
  4. Ignoring browser refresh: In-memory state does not automatically survive a refresh.
  5. Storing sensitive information in browser storage: Use appropriate security practices.
  6. Creating one enormous global store: Divide state into logical domains.
  7. Using global state for URL information: Search, filters and pagination often belong in the URL.
  8. Ignoring loading and error states: API-driven pages should handle both.
  9. Updating state incorrectly: Use immutable updates or the supported update patterns of the selected library.
  10. Persisting everything: Persist only the data that genuinely needs to survive a reload.

13. Recommended Architecture for a React Application

For a medium-sized application, a practical structure could look like this:

src/
│
├── components/
│   ├── Header.jsx
│   ├── Sidebar.jsx
│   └── Button.jsx
│
├── pages/
│   ├── HomePage.jsx
│   ├── ProductPage.jsx
│   ├── CartPage.jsx
│   └── ProfilePage.jsx
│
├── context/
│   └── UserContext.jsx
│
├── stores/
│   └── cartStore.js
│
├── services/
│   └── productService.js
│
├── hooks/
│   └── useProducts.js
│
├── routes/
│   └── AppRoutes.jsx
│
└── App.jsx

A possible division of responsibilities:

  • Local useState: Component-specific UI state.
  • Context: Simple shared application information.
  • Zustand or Redux Toolkit: Complex shared client state.
  • TanStack Query: API data and caching.
  • URL: Search, filters, sorting and pagination.

14. Interview Questions and Answers

Q1. How do you share state between multiple pages in React?

We can share state using React Context API, Redux Toolkit or Zustand. We can also use URL state when the information needs to be shareable or bookmarkable.

Q2. Does React Context maintain state when navigating between pages?

Yes. If the Context Provider is placed above the route components and remains mounted, its state is available across page navigation.

Q3. Does Redux state survive browser refresh?

No. Redux state is normally stored in memory. To preserve selected state after refresh, we need persistence or another storage mechanism.

Q4. What is the difference between Context API and Redux Toolkit?

Context API provides a built-in mechanism to share values across components. Redux Toolkit provides a more structured state management solution with a centralized store, reducers, actions and middleware support.

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

Client state is managed by the frontend, such as selected tabs and cart interactions. Server state originates from a backend, such as product lists and order details.

Q6. Why should we use TanStack Query?

It simplifies fetching, caching, synchronizing and updating server data. It also provides loading, error and background refetching capabilities.

Q7. When should we use URL state?

When the state should be shareable, bookmarkable or preserved through browser navigation, such as search terms, filters and pagination.

Q8. Can we use Context API and Redux Toolkit together?

Yes. For example, Context can manage theme preferences while Redux Toolkit manages complex application state. However, avoid introducing multiple solutions without a clear requirement.

Q9. What happens to useState when we navigate to another page?

If the component owning the state is unmounted, its local state is lost. If it remains mounted, its state remains. A shared state provider placed above the routes can retain data across route changes.

Q10. Which state management approach is best for a large React application?

There is no single best solution. Redux Toolkit or Zustand can manage complex client state, TanStack Query can manage server state, and URL state can handle shareable navigation information.

15. Final Takeaways

  • Use useState for local component state.
  • Use props for simple parent-child communication.
  • Use Context API for relatively simple shared state.
  • Use Redux Toolkit or Zustand for complex shared client state.
  • Use URL state for search, filters and pagination.
  • Use TanStack Query for API data and caching.
  • Use persistence only when state must survive browser refresh.

The most important principle: Do not make all state global. Keep state close to where it is used, and share it only when multiple components or pages genuinely need it.

🔙
How to Avoid Prop Drilling :👈 👉:How to Design Error Boundaries

Comments and Discussion