npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

use-s-react

v2.4.0

Published

useS: the definitive React hook for local and global state — effortless, zero boilerplate, one line, superpowers included

Readme

use-s-react

npm version npm downloads stars MIT license

What is useS?

Is a minimal yet powerful React hook for managing both local and global state — with zero boilerplate.

  • 🧠 Feels like useState, so it's instantly familiar.
  • 🚫 No Providers. No Context. No extra setup.
  • Scales globally without wrappers or nested trees.
  • 🧩 Works with any state shape: primitives, arrays, objects, deeply nested structures.
  • 🔁 Supports setState(prev => ...) logic.
  • 🧼 Built with TypeScript and powered by useSyncExternalStore and full-copy for deep reactivity and immutability.

It's a native and lightweight alternative to Zustand, Redux Toolkit, React Context, React useReducer and even useState itself — perfect for projects that need power and simplicity without the overhead.


📘 Want to understand use-s-react in depth? 👉 Visit the useS Documentation

📦 Installation

Install via npm or your preferred package manager:


npm i use-s-react

🚀 Quick Start

🔸 Import the hook


import { useS } from "use-s-react";

🔸 Local state (same as useState)


const [count, setCount] = useS(0);

🔸 Global state (via config object)


const [count, setCount] = useS({ value: 0, key: 'global-counter' });

✅ Best Practice: External Global Store

It is recommended to always pass the same reference of the initial value to useS instead of declaring the initial value directly inside the hook to improve performance. A good way to do this is by declaring an initialValue in your component or a centralized store.ts for the global state of your application:


// 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

♻️ Sharing Global State Between Components

🔸 ComponentA.tsx


import { useS } from "use-s-react";

export function ComponentA() {
  const [count, setCount] = useS({ value: 0, key: 'global-counter' });

  return (
    <div>
      <h3>Component A</h3>
      <p>Count: {count}</p>
      <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
    </div>
  );
}

🔸 ComponentB.tsx


import { useS } from "use-s-react";

export function ComponentB() {
  const [count] = useS({ value: 0, key: 'global-counter' });

  return (
    <div>
      <h3>Component B</h3>
      <p>Count from A: {count}</p>
    </div>
  );
}

🔁 Deep Updates & More

  • Updates are deep-merged using full-copy, preserving nested structures:

setUser({ info: { lang: "es" } }); // doesn't erase other info keys
  • You can also return a new state based on the previous:

setUser(prev => ({
  info: {
    lang: prev === 'en' ? 'es' : 'en',
    },
  })
);
  • Destructuring deeply

const [{ name, age }, setUser] = useS({
  value: {
    name: "John",
    age: 20
  },
  key: "global-user"
});
  • Infer state typing based on initial value

🗿 Immutability

useS shares a mutable reference to the component that is not the original state, which prevents you from breaking the no-mutation rule and allows you to do things like this:

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 (
    <div>
      <p data-testid="display">Items:{Array.from(mySet).join("-")}</p>
      <button onClick={handleAddItem}>Add Item</button>
    </div>
  );
}

You can do the same with other supported data types such as: array | object | map | date | regexp.

💿 Persistence

Starting with version 2.3.0, useS allows an optional parameter in the global state configuration that allows that state to be stored in the web browser's Local Storage.


const [count, setCount] = useS({ value: 0, key: 'global-counter', persist: true });

This allows useS to read localStorage to load previously stored valid values, as well as save new updates each time setState is executed.

🧪 Debugging (Optional)

Use debugGlobalStore() to inspect all global state in the console:


import { debugGlobalStore } from "use-s-react";

useEffect(() => {
  debugGlobalStore(); // logs all keys

  debugGlobalStore({ filterKey: "global-user" }); // only "global-user"

  debugGlobalStore({ consoleLog: true }); // plain logs
}, []);

✅ Fully compatible with React Native — debugGlobalStore() gracefully falls back to console.log when console.table is not available.

Starting with version 2.3.0, debugGlobalStore() displays the keys that are being persisted in localStorage.

🔍 console.table will be used when possible for better clarity.

🔧 API Summary

useS(initialValue: T) Creates a local state, just like useState (but with super powers).

useS({ value: T; key: string }) Makes the state globally available for use by other components. The key must be unique.

🛠️ Hook Config

useS supports an optional second configuration parameter that gives developers control over the default enhancements the hook provides.

useS(initialValue: T || { value: T; key: string },
  {
    mutableIn?: boolean;
    mutableOut?: boolean;
    forceUpdate?: boolean;
  }
)
  • mutableIn defaults to false. This means useS creates a clone of the initial value, and that new reference is used to create the state. This ensures immutability on input, allowing the developer to freely mutate the initial value elsewhere in the code without affecting the state. If mutableIn = true, useS will use the same reference of the initial value passed into the hook when creating the state.

  • mutableOut defaults to false. This means useS returns a clone of the original state. This ensures immutability on output, letting you mutate that returned value inside the component without affecting the state. If mutableOut = true, useS returns the original state instead.

  • forceUpdate defaults to false. This means that inside setState, useS validates the new value, and if it’s an object, it treats it as a partial of the previous value and merges it accordingly. If forceUpdate = true, anything you pass to setState will be used to update the state, with the same restrictions as React’s default useState.

📜 License

MIT © ChristBM