react-mutable-context

Create a React context that can accessed and mutated with hooks

Usage no npm install needed!

<script type="module">
  import reactMutableContext from 'https://cdn.skypack.dev/react-mutable-context';
</script>

README

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