DEV Community

KhaledSalem
KhaledSalem

Posted on

When Does Local State Become Shared State? A React State Ownership Guide

State Management Decision Authority — Part 02

Your React state doesn't need to be global just because two components need it.

In Part 1, useState vs useReducer: Stop Choosing Tools Before Understanding State, I explored an architectural idea I call the State Management Decision Authority: choosing state management strategies through consistent criteria rather than tool preferences.

One of those criteria deserves a deeper discussion:

State Ownership.

Because sharing state and globalizing state are two very different decisions.

1. The Checkout Problem

Imagine a checkout feature with three components:

function Checkout() {
  return (
    <>
      <ShippingForm />
      <OrderSummary />
      <PaymentSection />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Each component has a different responsibility.

  • ShippingForm collects the delivery address.
  • OrderSummary displays the shipping cost.
  • PaymentSection checks whether checkout requirements are satisfied.

But they all depend on some of the same information.

If the user changes the shipping country, the available shipping methods might change. The order summary may need to recalculate its totals, and payment might need to be disabled until a valid shipping option is selected.

The three components now need to coordinate.

Does that mean we should introduce a global store?

Not yet.

2. First Principle: Ownership Before Accessibility

Before choosing a tool, ask:

Who should own this state?

This is different from asking who needs to read it.

A component may consume state without owning its lifecycle or controlling its transitions.

For our checkout example, the checkout feature itself is a reasonable ownership boundary.

We can lift state to the nearest common ancestor:

import { useState } from "react";

function Checkout() {
  const [country, setCountry] = useState("EG");

  return (
    <>
      <ShippingForm
        country={country}
        onCountryChange={setCountry}
      />

      <OrderSummary country={country} />

      <PaymentSection country={country} />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now we have a single source of truth for country.

No Zustand. No Redux. No global Context provider.

Just state ownership aligned with the component tree.

Of course, the example is intentionally simplified. A real checkout flow would also need shipping options, validation rules, and order totals. Those can be derived or managed within the same feature boundary as appropriate.

Sharing state doesn't automatically require global ownership.

3. The Smallest Sufficient Ownership Boundary

Here's a principle I find useful:

Give each piece of state the smallest ownership boundary that satisfies its requirements.

Why the smallest?

Because expanding the ownership boundary also expands the potential dependency surface.

More components may gain access to the state. More logic may begin relying on its shape and behavior. Changes to that state can become harder to reason about.

That doesn't make shared state inherently bad.

It means accessibility should be intentional.

For example:

Requirement Potential ownership
Toggle a local dropdown Dropdown component
Coordinate shipping and payment Checkout feature
Share a wizard's progress across steps Wizard boundary
Display a notification across independent features Shared notification service or store
Cache fetched product data Server-state cache

Notice that ownership isn't determined by the number of components alone.

It's determined by the scope of coordination.

4. When useReducer Still Belongs Inside a Feature

What if our checkout state becomes more complicated?

Changing the shipping country might invalidate the selected shipping method.

Applying a discount might update the totals.

Submitting the checkout might require a valid combination of address, shipping option, and payment information.

Now we have related transitions and invariants.

This might justify useReducer:

const initialState = {
  country: "EG",
  shippingMethod: null
};

function checkoutReducer(state, action) {
  switch (action.type) {
    case "COUNTRY_CHANGED":
      return {
        ...state,
        country: action.country,
        shippingMethod: null
      };

    case "SHIPPING_SELECTED":
      return {
        ...state,
        shippingMethod: action.method
      };

    default:
      return state;
  }
}
Enter fullscreen mode Exit fullscreen mode

In a production implementation, SHIPPING_SELECTED should also validate that the selected shipping method is permitted for the current country, or accept only previously validated options.

The important architectural detail is that introducing useReducer changes how we manage transitions, not who needs to own the state.

We can continue keeping the reducer inside Checkout.

A complex state is not necessarily a global state.

5. When Context Becomes Useful

Now imagine our checkout feature grows deeper:

Checkout
  └── CheckoutLayout
       └── CheckoutSteps
            └── ShippingStep
                 └── ShippingForm
Enter fullscreen mode Exit fullscreen mode

Passing checkout state through components that don't use it can become inconvenient.

This is where Context might help.

import {
  createContext,
  useContext,
  useReducer
} from "react";

const CheckoutContext = createContext(null);

function CheckoutProvider({ children }) {
  const [state, dispatch] = useReducer(
    checkoutReducer,
    initialState
  );

  return (
    <CheckoutContext.Provider value={{ state, dispatch }}>
      {children}
    </CheckoutContext.Provider>
  );
}

function useCheckout() {
  const context = useContext(CheckoutContext);

  if (context === null) {
    throw new Error("Missing CheckoutProvider");
  }

  return context;
}
Enter fullscreen mode Exit fullscreen mode

We can place CheckoutProvider around the checkout feature rather than the entire application.

Context solves an accessibility problem: delivering a value to consumers deeper in a component tree.

It doesn't automatically solve complex transitions, and it isn't inherently a rendering optimization.

When a provider value changes, components consuming that Context are eligible to re-render. In performance-sensitive flows, we may need to split contexts, stabilize values, or use more selective subscription mechanisms.

Context changes how state is accessed. It doesn't require changing who owns it.

6. When an External Store Starts Making Sense

Suppose the requirements evolve again.

Several independent application features now need to coordinate shared client state.

Maybe a shopping cart is modified from product listings, product detail pages, and a persistent cart drawer.

A dedicated shared store may become easier to maintain than repeatedly lifting state or creating an increasingly broad Context.

This is where Zustand or Redux Toolkit becomes worth evaluating.

But the decision shouldn't be:

"We have five components consuming this state, so let's use Zustand."

A more useful question is:

Do we now have an ownership and subscription problem that our existing structure handles poorly?

Other considerations include:

  • Whether consumers need selective subscriptions
  • Whether cross-feature updates are becoming difficult to coordinate
  • Whether state transitions need stronger conventions or debugging capabilities
  • Whether the project already has a suitable established state management architecture
  • Whether the additional abstraction reduces more complexity than it introduces

An external store may be the right solution.

But it should be the result of a concrete architectural requirement.

7. Shared Client State Isn't Server State

There's one more boundary worth preserving.

Some data is shared because it originates from the server.

Product catalogs, user records, and remote inventory are examples.

That introduces concerns such as caching, stale data, refetching, invalidation, and synchronization.

For those cases, a server-state solution such as TanStack Query or RTK Query may be more appropriate than manually copying remote data into a general-purpose client store.

This isn't an either-or decision.

A real application can use local React state for a form, a shared client store for a cart, and a server-state cache for product information.

The important thing is to avoid giving one mechanism responsibilities it wasn't chosen to handle.

We'll explore this distinction later in the series.

8. A State Ownership Decision Framework

Before changing your state architecture, try answering these questions:

Question Possible direction
Does only one component need the state? Keep it local
Do siblings need to coordinate? Lift to their nearest common owner
Is passing data through intermediate components becoming cumbersome? Consider composition or Context
Are related transitions becoming difficult to maintain? Consider useReducer within the existing boundary
Are independent features coordinating shared client state? Evaluate an external store
Is the state primarily remote data? Evaluate server-state management

The framework is deliberately not a rigid decision tree.

These dimensions overlap, and different solutions can satisfy the same requirements.

Its purpose is to make our reasoning explicit.

Final Thought

One of the most expensive architectural decisions is making a local concern global before it needs to be.

Once unrelated features begin depending on a shared state boundary, changing that boundary can become harder.

My principle is simple:

Sharing state is a requirement. Globalizing state is an architectural decision.

And the goal should be:

The smallest sufficient ownership boundary.

That's how I'm applying the State Management Decision Authority introduced in Part 1.

Not by standardizing every tool, but by standardizing how we evaluate the problem.

Unify the decision criteria, not necessarily the tools.

What's next?

Part 03: Context vs Zustand vs Redux Toolkit — What Actually Justifies a Shared State Solution?

We'll go beyond feature ownership and explore how subscription behavior, transition complexity, tooling, and application boundaries influence the choice.

What makes you decide that React's built-in state management is no longer enough for a particular feature?

Top comments (10)

Collapse
 
davekurian profile image
Dave Kurian •

The COUNTRY_CHANGED reset is a useful invariant. I’d also test restore: a saved shipping method may fit the old country but fail for the current one, so validate it before payment becomes ready. Do you plan to cover that in the transition tests?

Collapse
 
khaledmsalem profile image
KhaledSalem •

Great catch, Dave! You're absolutely right. Restoring persisted state is effectively another state transition, and it shouldn't bypass the same invariants we enforce during user interactions.

I'd treat hydration as an explicit transition: validate the restored shipping method against the current country and available options, then either accept it or reset it before checkout can become payment-ready.

And yes, transition tests should cover this, including stale persisted data, invalid combinations, and changes in available shipping options.

This actually reinforces the broader principle of the series: ownership defines where state lives, but transition authority must protect its correctness regardless of where updates originate.

Really appreciate you pushing the discussion into these edge cases!

Collapse
 
davekurian profile image
Dave Kurian •

Treating hydration as a transition gives you one place to enforce the same country and shipping-method invariant as a user selection. The stale saved-method case sounds like the key regression test: restore under a country where it is unavailable and keep checkout from reaching payment-ready until it is cleared or replaced.

Thread Thread
 
khaledmsalem profile image
KhaledSalem •

Exactly, Dave! I'd also make the payment-ready condition depend on validated state, not just the presence of a shipping method.

That way, even if stale data gets restored, the checkout can't proceed until the current invariants are satisfied.

This is a great regression test for the transition contract. Appreciate you helping sharpen the example!

Thread Thread
 
davekurian profile image
Dave Kurian •

Treating hydration as an explicit transition also makes the invariant enforceable before payment is ready. I’d test restoring a saved shipping method that belonged to the previous country, then verify payment stays disabled until the current options are validated. That ties the regression test to the behavior it protects.

Thread Thread
 
khaledmsalem profile image
KhaledSalem •

Exactly, Dave! And I'd take that test one step further: verify that payment remains disabled while the restored shipping method is being validated, not just when validation fails.

That way, neither stale state nor a temporary "unknown" validation status can accidentally make checkout payment-ready.

It's a great example of why correctness should be enforced at the transition boundary rather than depending on individual UI components to remember the rules.

Really appreciate how you've helped turn this example into a concrete regression-testing scenario!

Collapse
 
idanshalem profile image
Idan Shalem •

If the same checkout can be open in two tabs of the same app, tree-based ownership stops at the tab. A country change in tab A would not reach tab B unless something syncs it, so tab B's summary could show the old country until reload. Hydrating from persisted state fixes a fresh tab, not two live ones. Does your 'smallest sufficient boundary' include other open tabs of the same app, or stop at the tab? I maintain react-broadcast-sync, which keeps one value in sync across same-origin tabs over BroadcastChannel; a newly opened tab asks open tabs for the current value and keeps its default if none answers.

Collapse
 
khaledmsalem profile image
KhaledSalem •

Great point, Idan! The smallest sufficient ownership boundary should be defined by consistency requirements, not necessarily by the React component tree.

If checkout state must remain consistent across tabs, then the coordination boundary extends beyond a single tab.

BroadcastChannel is a good transport for that, but synchronization also needs rules for concurrent updates, stale messages, and validation. Otherwise, we're just distributing potentially inconsistent state.

I also like your distinction between hydration and live synchronization. Restoring the latest known state solves a different problem from coordinating two active tabs.

This is exactly why I think ownership, synchronization, and transition correctness should remain separate architectural decisions.

Thanks for bringing a real-world edge case into the discussion!

Collapse
 
idanshalem profile image
Idan Shalem •

Exactly - the sync rules are where the design weight sits. In react-broadcast-sync's useSyncedState every write carries a logical (clock, source) version, so concurrent writes converge to one deterministic winner instead of trying to preserve every edit - two tabs incrementing a counter at once lose one intent, which is why anything that can't lose a write still belongs on the server. Stale messages are deduped, and an old version can't overwrite a newer local edit. Validation is opt-in if you want incoming payloads checked before they land. The transport is just BroadcastChannel; the consistency story lives in those version rules.

Thread Thread
 
khaledmsalem profile image
KhaledSalem •

That's a really important distinction, Idan!

A deterministic winner gives us convergence, but not necessarily preservation of every user intent. Your counter example makes that trade-off very clear.

I also like that you've separated transport from consistency: BroadcastChannel moves updates, while logical versions determine which update wins.

I'd add one more boundary to the decision framework: conflict semantics. Before choosing a synchronization mechanism, we should decide whether the domain allows last-write-wins, requires merging operations, or needs server-side coordination.

And even with deterministic convergence, incoming state still needs to satisfy the domain's invariants.

This is exactly the kind of real-world example I want the series to address. Thanks for sharing the implementation details!