Package Exports
- react-happy-global-state
- react-happy-global-state/dist/index.cjs.js
- react-happy-global-state/dist/index.esm.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-happy-global-state) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Quick Features 🥳
- Manage your global state, just like using the useState hook.
- Built with typescript, provide type protection, code autocompletion, make your app robust.
- Less than 1kB size.
How to use 📖
Install package
npm install react-happy-global-state
Create your store.ts
import { createGlobalState } from 'react-happy-global-state';
// define you GlobalState type
type GlobalState = {
count: number;
};
// set your default global state
const DEFAULT_GLOBAL_STATE: GlobalState = {
count: 0,
};
export const { GlobalStateProvider, useGlobalState } = createGlobalState({
defaultState: DEFAULT_GLOBAL_STATE,
});
Use GlobalStateProvider to wrap your App
import React from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App';
import { GlobalStateProvider } from './store';
const container = document.getElementById('root');
const root = createRoot(container!);
root.render(
<React.StrictMode>
{/* use GlobalStateProvider wrap your App */}
<GlobalStateProvider>
<App />
</GlobalStateProvider>
</React.StrictMode>,
);
Use useGlobalState in your Component
import React from 'react';
import { useGlobalState } from './store';
export const Counter = () => {
// use useGlobalState hook to get/set your global state
const [count, setCount] = useGlobalState('count');
return (
<div>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
};
Click here to try it by yourself.