https://www.npmjs.com/package/swr-global-state
yarn add swr-global-state
Usage
Create a store object
Create a new file for your global state on your root directory. Example: stores/app.js
// file: stores/app.js
export const APP_COUNT = {
key: "@app/count", // (Required) state key
initial: 0, // <- (Required) initial state
persist: false // <- (Optional) if you want to persist the state to local storage, then set it to true.
};
Using store on your component
// file: components/SetCountComponent.js
import { useStore } from "swr-global-state";
import { APP_COUNT } from "stores/app";
function SetCountComponent() {
const [count, setCount] = useStore(APP_COUNT);
return (
<div>
<button onClick={() => setCount(count - 1)}>
(-) Decrease Count
</button>
<button onClick={() => setCount(count + 1)}>
(+) Increase Count
</button>
</div>
);
}
export default SetCountComponent;
// file: components/GetCountComponent.js
import { useStore } from "swr-global-state";
import { APP_COUNT } from "stores/app";
function GetCountComponent() {
const [count] = useStore(APP_COUNT);
return (
<div>
<p>Current Count: {count}</p>
</div>
);
}
export default GetCountComponent;
Best Practice
Custom hooks
Instead of creating store object in stores/app.js file, you can create a custom hooks with createStore(). Example: stores/count.js.
// file: stores/count.js
import { createStore } from "swr-global-state";
const useCount = createStore({
key: "@app/count", // (Required) state key
initial: 0, // <- (Required) initial state
persist: true // <- (Optional) if you want to persist the state to local storage, then set it to true.
});
export default useCount;
Using store on your component
// file: components/SetCountComponent.js
import useCount from "stores/count";
function SetCountComponent() {
const [, setCount] = useCount(); // <- `[, ]` skipping first index of the array.
return (
<div>
<button onClick={() => setCount(prev => prev - 1)}>
(-) Decrease Count
</button>
<button onClick={() => setCount(prev => prev + 1)}>
(+) Increase Count
</button>
</div>
);
}
export default SetCountComponent;
// file: components/GetCountComponent.js
import useCount from "stores/count";
function GetCountComponent() {
const [count] = useCount();
return (
<div>
<p>Current Count: {count}</p>
</div>
);
}
export default GetCountComponent;