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

galactic-state

v2.0.2

Published

Simplified global React state

Downloads

335

Readme

Galactic State

A "global" state library for React, with an API similar to useState.

NPM npm NPM

Install

npm i galactic-state

Usage

createGalactic receives a single argument, which corresponds to the default state value. It returns a tuple with a hook in the first position that works like useState, but whose state will be "global", ie any component that uses it will update when its value gets updated.

// state.js
import { createGalactic } from 'galactic-state';

export const [useEmail] = createGalactic('');
export const [usePassword] = createGalactic('');

...
// Components.jsx
import { useEmail, usePassword } from 'src/state';

function Login() {
    const [email, setEmail] = useEmail();
    const [password, setPassword] = usePassword();

    return (
        <div>
          <input 
            type='email'
            onChange={e => setEmail(e.target.value)}
            value={email}
          />
          <input 
            type='password'
            onChange={e => setEmail(e.target.value)}
            value={password}
          />
        </div>
    );
}

function OtherComponent() {
    const [email] = useEmail();

    return (
        <h1>{email}</h1> // will update when `setEmail` is called in `Login` Component
    );
}

function App() {
    return (
        <div>
            <OtherComponent />
            <Login />
        </div>
    );
}

Setter

The second value in the tuple returned from createGalactic is a setter function that can be called from anywhere. This is the exact same setter that is returned from the generated hook, and it will have the same function.

If you have a component that is just setting state and not consuming the state value, you can use this setter instead to prevent unnecessary rerendering of your component.

You could also use this within a websocket connection to sync your server state and your client state.

// state.js
export const [useIsAuthenticated, setIsAuthenticated] = createGalactic(false);

// Login.jsx
import { setIsAuthenticated } from 'src/state';

function Login() {
    ...

    return (
        <form onSubmit={async () => {
            const isAuthenticated = await serverValidateCredentials(email, password);
            setIsAuthenticated(isAuthenticated);
        }}>
            ...
        </form>
    )
}

// Logs out user from the server (for security reasons).
ServiceAuthenticationValidWS.subscribe(isAuthenticated => {
    setIsAuthenticated(isAuthenticated)
})

Observer

The third value in the tuple is an observer, which can be used to subscribe to state changes from anywhere in the app, not necessarily within a component.

const [useEmail, setEmail, emailObserver] = createGalactic('');

...

emailObserver.subscribe(email => console.log(email)); // will log email when components update it.

function getEmailValue() {
    return emailObserver.value; // returns the current email value when called.
}

FAQ

Why this instead of Context?

React Context's API can be a bit clunky to use. If you have contexts that depend on each other, it can be very tricky to get them to work. You also still have some boilerplate (though not as much as Redux), a learning curve, and you often end up with lots of imports to consume your context. Context can also result in performance issues since providers will rerender the whole app when they render if you're wrapping all your components.

Galactic State provides a much simpler API and intuitive API which can help create a more performant application.

Why "Galactic"?

"Global" state has bad connotations, and it needed to have a differentiating name.