Create a React context that can be accessed and mutated with hooks.
$ npm install --save react-mutable-context
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);