Skip to content

Latest commit

 

History

History
144 lines (109 loc) · 2.77 KB

1.getting-started.md

File metadata and controls

144 lines (109 loc) · 2.77 KB

Quick Start

Welcome to the quick guide for using this library.

Important: Please check out https://r18gs.vercel.app/ to learn how to use selectors.

Installation

To get started, you can install the package via your preferred package manager. Here are a few examples:

$ pnpm add r18gs

or

$ npm install r18gs

or

$ yarn add r18gs

Usage

Utilize this hook similarly to the useState hook. However, ensure to pass a unique key, unique across the app, to identify and make this state accessible to all client components.

const [state, setState] = useRGS<number>("counter", 1);

You can access the same state across all client-side components using a unique key.

It's advisable to store your keys in a separate file to prevent typos and unnecessary conflicts.

Using selectors

You can create helper store like below

import { useRGS } from "r18gs";

interface MyStore {
  count: number;
  name: string;
  user: {
    name: string;
    age: number;
  };
}

export const useStore = (includeRegExp?: RegExp | null | 0, excludeRegExp?: RegExp) =>
  useRGS<MyStore>(
    "my-store-with-selectors",
    {
      count: 0,
      name: "John",
      user: {
        name: "John",
        age: 30,
      },
    },
    includeRegExp,
    excludeRegExp,
  );

And use it like

const [{ count }, setState] = useStore(/^count$/);

or

import { listToRegExp } from "r18gs/dist/utils";
...
const [{ count }, setState] = useStore(listToRegExp([count]));

Important: Please check out https://r18gs.vercel.app/ to learn how to use selectors.

Initializing the state with a function

In some cases you might want to initialize the state with a function, for example, when reading from localStorage. We support initializer function as well.

const [state, setState] = useRGS<number>("counter", () =>
  typeof localStorage === "undefined" ? 1 : localStorage.getItem("counter") ?? 1,
);

Example

// constants/global-states.ts
export const COUNTER = "counter";
// components/display.tsx
"use client";

import { useRGS } from "r18gs";
import { COUNTER } from "../constants/global-states";

export default function Display() {
  const [count] = useRGS<number>(COUNTER);
  return (
    <div>
      <h2>Client Component 2</h2>
      <b>{count}</b>
    </div>
  );
}
// components/counter.tsx
"use client";

import { useRGS } from "r18gs";
import { COUNTER } from "../constants/global-states";

export default function Counter() {
  const [count, setCount] = useRGS(COUNTER, 0);
  return (
    <div>
      <h2>Client Component 1</h2>
      <input
        onChange={e => {
          setCount(parseInt(e.target.value.trim()));
        }}
        type="number"
        value={count}
      />
    </div>
  );
}