### Install use-s-react Source: https://github.com/christbm/use-s/blob/main/README.md Install the use-s-react package using npm or your preferred package manager. ```bash npm i use-s-react ``` -------------------------------- ### Immutable Updates with Mutable Data Types (Set Example) Source: https://github.com/christbm/use-s/blob/main/README.md Demonstrates how to handle mutable data types like Set by creating a new instance or modifying the existing one and then passing it to the setter function to trigger a state update. ```tsx const initialValue = new Set([1, 2, 3, 4]); export function LocalStateTypeSet() { const [mySet, setMySet] = useS(initialValue); const handleAddItem = () => { mySet.add(5); // mutating the mySet state directly setMySet(mySet); // setting the mutated state to generate a valid change }; return (

Items:{Array.from(mySet).join("-")}

); } ``` -------------------------------- ### Import the useS Hook Source: https://github.com/christbm/use-s/blob/main/README.md Import the useS hook from the 'use-s-react' library to start managing state. ```tsx import { useS } from "use-s-react"; ``` -------------------------------- ### Sharing Global State Between Components (ComponentA) Source: https://github.com/christbm/use-s/blob/main/README.md Component A demonstrates how to initialize and update a global state using useS with a configuration object. Changes here will reflect in other components using the same global key. ```tsx import { useS } from "use-s-react"; export function ComponentA() { const [count, setCount] = useS({ value: 0, key: 'global-counter' }); return (

Component A

Count: {count}

); } ``` -------------------------------- ### Enable Local Storage Persistence with useS Source: https://github.com/christbm/use-s/blob/main/README.md Configure a global state to persist its value in the browser's Local Storage by setting the 'persist' option to true. This allows the state to be loaded from and saved to Local Storage automatically. ```tsx const [count, setCount] = useS({ value: 0, key: 'global-counter', persist: true }); ``` -------------------------------- ### Local State Management with useS Source: https://github.com/christbm/use-s/blob/main/README.md Use useS like useState for managing local component state. It accepts an initial value and returns a state variable and a setter function. ```tsx const [count, setCount] = useS(0); ``` -------------------------------- ### Configure useS Hook Options Source: https://github.com/christbm/use-s/blob/main/README.md Customize the behavior of the useS hook using its optional second configuration parameter. Options include mutableIn, mutableOut, and forceUpdate to control state immutability and update behavior. ```ts useS(initialValue: T || { value: T; key: string }, { mutableIn?: boolean; mutableOut?: boolean; forceUpdate?: boolean; } ) ``` -------------------------------- ### Typed State Management with TypeScript Source: https://context7.com/christbm/use-s/llms.txt Demonstrates how use-s-react infers state types from initial values and accepts partial updates for nested objects, simplifying state management in TypeScript projects. ```tsx import { useS } from "use-s-react"; import type { GlobalStateConfig, HookConfig, SetStateAction } from "use-s-react"; // re-exported from dist type User = { name: string; age: number; prefs: { lang: "en" | "es"; notifications: boolean }; }; const userConfig: GlobalStateConfig = { value: { name: "Alice", age: 28, prefs: { lang: "en", notifications: true } }, key: "typed-user", persist: true, }; function TypedComponent() { // T is inferred as User — setState accepts Partial automatically const [user, setUser] = useS(userConfig); // ✅ Partial nested update — TypeScript won't complain const disableNotifs: SetStateAction = { prefs: { notifications: false } }; // ✅ Functional update — also partial const toggleLang: SetStateAction = prev => ({ prefs: { lang: prev.prefs.lang === "en" ? "es" : "en" }, }); return (

{user.name} — {user.prefs.lang}

); } ``` -------------------------------- ### Global State Management with useS Source: https://github.com/christbm/use-s/blob/main/README.md Manage global state by providing a configuration object with a 'value' and a unique 'key' to the useS hook. ```tsx const [count, setCount] = useS({ value: 0, key: 'global-counter' }); ``` -------------------------------- ### Centralized Global Store Configuration Source: https://github.com/christbm/use-s/blob/main/README.md Define initial values for global state in a centralized store file for better performance and organization. Import and use these initial values with useS. ```tsx // store.ts export const store = { globalCounter: { value: 0, key: 'global-counter', }, globalUser: { value: { name: "John", age: 30, }, key: 'global-user', } }; // Then import the hook import { store } from "./store"; // And use it in your Component: const [count, setCount] = useS(store.globalCounter); // Global const [countLocal, setCountLocal] = useS(store.globalCounter.value); // Local ``` -------------------------------- ### useS Hook for Global State Management Source: https://context7.com/christbm/use-s/llms.txt Use this pattern to share state across components without prop drilling or context wrappers. Define a central store configuration object for shared state keys and initial values. ```tsx // Recommended: declare the config in a central store.ts to reuse the same reference // store.ts export const store = { counter: { value: 0, key: "global-counter" }, user: { value: { name: "John", age: 30, prefs: { lang: "en" } }, key: "global-user", }, }; ``` ```tsx // ComponentA.tsx — writes to global state import { useS } from "use-s-react"; import { store } from "./store"; function ComponentA() { const [count, setCount] = useS(store.counter); return (

A sees: {count}

); } ``` ```tsx // ComponentB.tsx — reads the same global state, no props needed import { useS } from "use-s-react"; import { store } from "./store"; function ComponentB() { const [count] = useS(store.counter); return

B sees: {count}

; // Renders automatically whenever ComponentA updates the counter } ``` ```tsx // Deep partial update on a global object state function LanguageSwitcher() { const [user, setUser] = useS(store.user); const toggleLang = ( setUser(prev => ({ prefs: { lang: prev.prefs.lang === "en" ? "es" : "en" } })) ); return (

Language: {user.prefs.lang}

); } ``` -------------------------------- ### Inspect Global State with debugGlobalStore Source: https://context7.com/christbm/use-s/llms.txt The `debugGlobalStore` function prints the global store to the console using `console.group` and `console.table`. It also shows persisted keys and accepts options to filter by key or force `console.log` output. ```tsx import { useS, debugGlobalStore } from "use-s-react"; import { useEffect } from "react"; function DevPanel() { const [, setCount] = useS({ value: 0, key: "counter" }); const [, setUser] = useS({ value: { name: "Ana" }, key: "user", persist: true }); useEffect(() => { // Dump all global state to console — uses console.table when available debugGlobalStore(); // Console output: // [ 🔐 Persistent Keys ] LocalStorage // ["user"] // [ 🌐 Global State ] useS() // 🔑 counter (number) → 0 // 🔑 user (object) → { name: "Ana" } // Filter to a single key debugGlobalStore({ filterKey: "user" }); // Only prints the "user" entry // Force console.log instead of console.table (React Native compatible) debugGlobalStore({ consoleLog: true }); }, []); return ; } ``` -------------------------------- ### Persistent Global State with useS Source: https://context7.com/christbm/use-s/llms.txt Enable localStorage synchronization by setting `persist: true` in the global config. useS reads stored values on mount and saves on every `setState` call. Functions are not persisted. ```tsx import { useS } from "use-s-react"; // store.ts export const store = { theme: { value: "light" as "light" | "dark", key: "app-theme", persist: true }, cart: { value: { items: [] as string[], total: 0 }, key: "shopping-cart", persist: true, }, }; // ThemeToggle.tsx — persists across page reloads function ThemeToggle() { const [theme, setTheme] = useS(store.theme); return ( ); } // Cart.tsx — cart state survives hard refreshes function Cart() { const [cart, setCart] = useS(store.cart); const addItem = (item: string) => setCart(prev => ({ items: [...prev.items, item], total: prev.total + 1, })); return (

Items: {cart.items.join(", ")}

); } // localStorage key "shopping-cart" is automatically kept in sync ``` -------------------------------- ### Sharing Global State Between Components (ComponentB) Source: https://github.com/christbm/use-s/blob/main/README.md Component B demonstrates how to consume a global state initialized by another component. It reads the 'global-counter' state, showing the updated value. ```tsx import { useS } from "use-s-react"; export function ComponentB() { const [count] = useS({ value: 0, key: 'global-counter' }); return (

Component B

Count from A: {count}

); } ``` -------------------------------- ### SSR Integration with Next.js Source: https://context7.com/christbm/use-s/llms.txt Shows how to use use-s-react in an SSR component boundary in Next.js 15 App Router. It ensures server-side rendering safety by using `getServerSnapshot` and gating `localStorage` access. ```tsx // app/page.tsx (Next.js 15 App Router — SSR component boundary) "use client"; import { useS } from "use-s-react"; // store.ts — shared between server and client modules export const store = { visits: { value: 0, key: "page-visits", persist: true }, }; export default function Page() { // Safe in Next.js 15, Remix, or any SSR framework const [visits, setVisits] = useS(store.visits); // On server: renders with initial value (0) — no localStorage access // On client: re-hydrates from localStorage if a prior value exists return (

Visits this session: {visits}

); } ``` -------------------------------- ### useS Hook Configuration (HookConfig) Source: https://context7.com/christbm/use-s/llms.txt Override default immutability and update behaviors using HookConfig. Options include `mutableIn`, `mutableOut`, and `forceUpdate` for performance-sensitive scenarios or external mutable data. ```tsx import { useS } from "use-s-react"; const externalRef = { score: 100 }; function Example() { // mutableIn: true — useS uses the exact reference passed, no deep copy on init const [stateA, setA] = useS(externalRef, { mutableIn: true }); // mutableOut: true — returns the real state reference (no copy); mutate with care const [stateB, setB] = useS({ x: 1, y: 2 }, { mutableOut: true }); // stateB IS the internal state; mutating it directly affects the store // forceUpdate: true — bypasses deep-merge and validation; replaces state as-is const [list, setList] = useS([1, 2, 3], { forceUpdate: true }); const replaceList = () => setList([10, 20]); // always triggers a re-render // Combining options for a high-performance external data flow const [data, setData] = useS( { value: { count: 0 }, key: "perf-state" }, { mutableIn: true, mutableOut: true } ); return (

Score: {stateA.score}

List: {list.join(", ")}

); } ``` -------------------------------- ### Deep Updates with Object Merging Source: https://github.com/christbm/use-s/blob/main/README.md useS performs deep-merging for object updates using full-copy. Providing a partial object to the setter will merge it with the existing state, preserving other properties. ```tsx setUser({ info: { lang: "es" } }); // doesn't erase other info keys ``` -------------------------------- ### useS Hook for Primitive Local State Source: https://context7.com/christbm/use-s/llms.txt Use this for managing simple, component-local primitive states like numbers or strings. It behaves like useState but ensures deep immutability. ```tsx import { useS } from "use-s-react"; // Primitive local state function Counter() { const [count, setCount] = useS(0); return (

Count: {count}

); } ``` -------------------------------- ### Debug Global Store with debugGlobalStore Source: https://github.com/christbm/use-s/blob/main/README.md Use the debugGlobalStore function to inspect all global states or filter by a specific key. It gracefully falls back to console.log in React Native environments and indicates persisted keys. ```tsx import { debugGlobalStore } from "use-s-react"; useEffect(() => { debugGlobalStore(); // logs all keys debugGlobalStore({ filterKey: "global-user" }); // only "global-user" debugGlobalStore({ consoleLog: true }); // plain logs }, []); ``` -------------------------------- ### Updating State Based on Previous Value Source: https://github.com/christbm/use-s/blob/main/README.md The setter function returned by useS can accept a callback that receives the previous state, allowing for updates based on the current state value. ```tsx setUser(prev => ({ info: { lang: prev === 'en' ? 'es' : 'en', }, }) ); ``` -------------------------------- ### useS Hook for Object Local State Source: https://context7.com/christbm/use-s/llms.txt Manage component-local object states. Partial updates are automatically deep-merged, preserving other properties. ```tsx // Object local state — partial updates are deep-merged automatically function UserCard() { const [user, setUser] = useS({ name: "Alice", age: 30, address: { city: "NY" } }); return (

{user.name} — {user.address.city}

{/* Only updates address.city; other keys are preserved */}
); } ``` -------------------------------- ### useS Hook for Set/Map/Date Local State Source: https://context7.com/christbm/use-s/llms.txt Handles local state for mutable-friendly types like Set, Map, and Date. You can safely mutate the returned copy before passing it to the setter. ```tsx // Set / Map / Date local state — mutable-friendly pattern function TagManager() { const initialTags = new Set(["react", "typescript"]); const [tags, setTags] = useS(initialTags); const addTag = () => { tags.add("use-s-react"); // safe to mutate the returned copy setTags(tags); }; return ; } ``` -------------------------------- ### Destructuring Deeply Nested State Source: https://github.com/christbm/use-s/blob/main/README.md You can destructure deeply nested properties directly from the state returned by useS when managing objects. This requires providing the initial nested structure. ```tsx const [{ name, age }, setUser] = useS({ value: { name: "John", age: 20 }, key: "global-user" }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.