1.0.1 • Published 5 years ago

react-mutable-context v1.0.1

Weekly downloads
61
License
MIT
Repository
github
Last release
5 years ago

react-mutable-context

NPM version build status Test coverage npm download

Create a React context that can be accessed and mutated with hooks.

Installation

$ npm install --save react-mutable-context

Usage

import { createMutableContext } from 'react-mutable-context';

const context = createMutableContext('black');

const { Provider: ColorProvider, use: useColor } = context;

function App() {
  return (
    <ColorProvider>
      <ColorUser />
    </ColorProvider>
  );
}

function ColorUser() {
  const [color, setColor] = useColor();

  const handleClick = () => setColor('red');

  return (
    <div style={{ color }}>
      <div>Using color from the context!</div>
      <div>
        <button type="button" onClick={handleClick}>
          Change color
        </button>
      </div>
    </div>
  );
}

// The value can also be read and changed outside of React components
setTimeout(() => {
  console.log(context.getValue()); // 'black'
  context.setValue('green');
  console.log(context.getValue()); // 'green'
}, 1000);

License

MIT