React Legacy Context Polyfill

0.3.0 · abandoned · verified Sun Apr 19

The `create-react-context` package provides a polyfill, or more accurately, a ponyfill, for the modern React Context API (`React.createContext`) introduced in React 16.3.0. It allows applications running on older versions of React (specifically React 0.14.0, 15.0.0, and pre-16.3.0 versions of React 16) to utilize the `Provider` and `Consumer` pattern for prop drilling and state management, mimicking the official API's behavior. The current stable version is 0.3.0, and given its nature as a polyfill for a now-native feature, it is unlikely to receive significant new feature development; its release cadence is effectively dormant. Its primary differentiation was enabling forward-compatible context usage before React 16.3 became widespread, bridging the gap for applications migrating or needing modern context features in legacy environments, while explicitly *not* polyfilling other React 16+ APIs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a context, provide a value with `Context.Provider`, and consume it with `Context.Consumer` using a simple theme toggler example, adapted for TypeScript.

import React, { useState, type ReactNode } from 'react';
import createReactContext, { type Context } from 'create-react-context';

type Theme = 'light' | 'dark';
const ThemeContext: Context<Theme> = createReactContext('light');

function ThemeToggler({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light');

  const toggleTheme = () => {
    setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={theme}>
      <button onClick={toggleTheme}>
        Toggle theme (current: {theme})
      </button>
      {children}
    </ThemeContext.Provider>
  );
}

function Title({ children }: { children: ReactNode }) {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>
          {children}
        </h1>
      )}
    </ThemeContext.Consumer>
  );
}

// Example usage in an App component
function App() {
    return (
        <ThemeToggler>
            <Title>Hello Context!</Title>
        </ThemeToggler>
    );
}

export default App;

view raw JSON →