#react#hooks#context

Reuse Hooks with Shared State using Context

February 9, 2026·2 min read

I recently encountered a problem where I wanted to reuse a hook's logic but ensure that all consumers shared the exact same state. A simple hook call in multiple components creates isolated state for each instance. To solve this, I designed a solution using a ContextProvider architecture.

The Architecture

The solution revolves around a ContextProvider component that performs two critical functions:

  1. Stores the source of truth locally. This is the raw state that drives the application.
  2. Provides memoized methods. These methods calculate the final, presentation-ready state from the raw source of truth.

This provider then:

  • Exposes the final state (presentation-ready) via a standard React Context.
  • Exposes methods for updating the source-of-truth state.

Why This Works

This approach has several key benefits:

  • Singleton Context: The state exists in one place (the provider), making it a effectively a singleton for that subtree.
  • Efficient Calculation: By using memoization within the provider, the expensive calculation to derive the presentation state happens only once, not in every consumer.
  • Clean Consumption: Consumers simply read the presentation-ready state. They don't need to know about the raw data or the derivation logic.
  • Correct Updates: Child components automatically subscribe to context changes. When the presentation-ready state updates (due to a source-of-truth change), all consumers re-render with the new data.

This pattern is cleaner than Redux for simple shared state and more robust than simple prop drilling or global variables.