Skip to content

mucsi96/react-create-shared-state

Repository files navigation

react-create-shared-state

npm version Build Status

This package allows sharing data between components with hooks. In many cases leads to more simple implementation compared to Context API. createSharedState creates a hook very similar to useState but with sync state across hook instances. Setting a value in one component will result re-rendering every component which uses the same hook.

image

Side-by-side comparison with Context API

image

Usage

Demo

import { createSharedState } from 'react-create-shared-state';

const useTheme = createSharedState('light');

function App {
  return (
    <Toolbar />
    <ThemeSwitch />
  );
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const [theme] = useTheme();
  return <Button theme={theme} />;
}

function ThemeSwitch {
  const [theme, setTheme] = useTheme();
  return (
    <Button
      onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
    >
      {theme}
    </Button>
  );
}

About

useState but with shared state across components

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •