Enhance your store's functionality by utilizing either the create
function, withPlugins
function, or the useRGSWithPlugins
hook from r18gs/dist/with-plugins
. This enables features such as storing to local storage, among others.
// store.ts
import { create } from "r18gs/dist/with-plugins";
import { persist } from "r18gs/dist/plugins"; /** You can create your own plugin or import third-party plugins */
export const useMyPersistentCounterStore = create<number>("persistent-counter", 0, [persist()]);
Now you can utilize useMyPersistentCounterStore
similar to useState
without specifying an initial value.
// inside your component
const [persistedCount, setPersistedCount] = useMyPersistentCounterStore();
This function is beneficial if your requirements dictate that your key
and/or initial value will depend on some props, etc. Or for some other reason you want to initialize the store from within a component (You need to use some variables available inside the component).
import { useRGSWithPlugins } from "r18gs/dist/with-plugin";
export function MyComponent(props: MyComponentProps) {
const [state, setState] = useRGSWithPlugins(
props.key,
props.initialVal,
props.plugins,
props.doNotInit,
);
// ...
}
In some cases, you may not want to initialize the store immediately. In such cases, you can pass the fourth argument (doNotInit
) as true
. The default value is false.
- When this argument is set to
true
, the store is created, but the setter function is set to null. Thus, you can access the initial value set by the first component that triggered this hook. However, it cannot be modified until the store is initialized, i.e., the hook is invoked by a component settingdoNotInit
to false (or skipping this argument).
Use case: When you need that the store be used in many components, however, it should be initialized in a particular component only.
This is a utility function that will be very helpful when you want to use the useRGSWithPlugins
hook with the same plugins in multiple components.
// custom hook file, e.g., store.ts
export const useMyRGS = withPlugins([plugin1, plugin2, ...]);
export function MyComponent(props: MyComponentProps) {
const [state, setState] = useMyRGS(props.key, props.initialVal, props.doNotInit);
// ...
}
You can also create your own plugins. Refer to Creating Plugins.