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 🙏

© 2024 – Pkg Stats / Ryan Hefner

truly-global-state

v1.0.7

Published

A truly global state management library for React with pub/sub workflow

Downloads

9

Readme

Truly Global State for React

A pub/sub-based global state management library for React with almost no boilerplate code and access to state from anywhere.

npm install truly-global-state # or yarn add truly-global-state

Create the store

Configure your store using a simple object, with initial values for all store keys. Actions can also be defined, these are just functions in the object where you can use this to modify the state. If you are using arrow function expressions you will have to use store.state instead, as your function will not have access to the correct this

// store.ts

import { createStore } from "truly-global-state"

export const store = createStore({
    count: 0,
    // actions are just normal functions
    double() {
        this.count *= 2
    },
    // or with arrow function expressions:
    triple: () => {
        store.state.count *= 3
    }
})

Use in your React components

Components that read from the store will need to subscribe to it. Every time the value changes, subscribed components will re-render themselves along with all their children. Use the subscribeTo(keys: string[]) method to listen to changes for specific keys in the store, or use the subscribeToAll() method to update whenever anything changes.

// DisplayCount.tsx

import { store } from "./store"

export function DisplayCount() {
    store.subscribeTo(['count'])
    
    return (
        <div>
            Count: {store.state.count}
        </div>
    )
}

A quick and dirty way to get started for small projects would be to use subscribeToAll on your root-level component, this way you won't have to worry about subscribing each component separately. However, beware that as your app grows this could cause performance issues, since everything re-renders every time anything is changed.

// App.tsx

import { store } from "./store"
import { Buttons } from "./Buttons.tsx"
import { DisplayCount } from "./DisplayCount.tsx"

export function App() {
    store.subscribeToAll()

    return (
        <>
            <Buttons />
            <DisplayCount />
        </>
    )
}

Components that write to the store don't need to be subscribed to it (unless they also read from it!), this means that the component will not be re-rendered when store values are changed.

To change a store value, just set it!

To submit an action, just call it!

// Buttons.tsx

import { store } from "./store"

export function Buttons() {
    return (
        <>
            <button onClick={() => store.state.count += 1}>
                increment
            </button>
            <button onClick={() => store.state.double()}>
                double
            </button>
        </>
    )
}

Use in your functions!

Because the store has been exposed globally, you can use it in functions that don't qualify as React components. (Something you can't do with hooks!)

// increaseBy5.ts

import { store } from "./store"

export function increaseBy5() {
    store.state.count += 5
}

Fully type safe

Typescript will give you correct type annotations for all store values, or shout at you if you mispell one of the store keys.

const count = store.state.count // count: number
// Property 'cont' does not exist on type '{ count: number; double: () => void; }'. Did you mean 'count'?
const count = store.state.cont

When subscribing a component, typescript will also check your store keys.

// Type '"cont"' is not assignable to type '"count" | "double"'. Did you mean '"count"'?
store.subscribeTo(['cont'])

Reactivity for deeply nested state and arrays

Updates to the children of store values are automatically detected.

// store.ts

export const store = defineStore({
    array1: [1, 2, 3],
    array2: [[5, 6], [7, 8]],
    deeply: {
        nested: {
            object: 'change me!'
        }
    },
})
// udpateComplexValues.ts

export function udpateComplexValues() {
    store.state.array1.push(4)
    store.state.array2[0][0] = 10
    store.state.deeply.nested.object = 'changed!'
}

Built-in localStorage support

Specify an array of key names for all the store values you want to save into localStorage. When the user comes back in a new session, saved values will be restored.

// store.ts

import { createStore } from "truly-global-state"

export const store = createStore(
    {
        count: 0,
        double() {
            this.count *= 2
        },
    },
    {
        // count will be saved in localStorage every time it is updated
        localStorage: {
            keys: ['count']
            localStoragePrefix: 'prefix-', // optional: prepend a string to the localStorage key name, useful if there could be collisions with existing key names in your app
        }
    }
)

Built-in undo/redo support

Specify an array of key names for all the store values you want to save into the history. Call store.saveHistory() whenever you want to add the current state to the history stack. Call store.undo() or store.redo() to undo/redo, and call store.canUndo() or store.canRedo() to give user feedback about the history.

// store.ts

import { createStore } from "truly-global-state"

export const store = createStore(
    {
        count: 0,
        double() {
            this.count *= 2
        },
    },
    {
        localStorage: { keys: ['count'] }
        // count will be added to the history whenever store.saveHistory() is called
        undoRedo: {
            keys: ['count'],
            useLocalStorage: true, // optional (default = false): save the history stack to localStorage
            localStorageKey: 'myHistory', // optional (default = 'history'): specify the localStorage key in case you are already using 'history' for something
            maxLength: 10, // optional (default = unlimited): specify how many times the user can undo
        }
    }
)