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

rgstate

v1.0.12

Published

Global state for React with a 2 line hook implementation

Downloads

32

Readme

RGState

React Global State

npm install rgstate --save
yarn add rgstate

The simplest implementation

import React, { useEffect } from 'react';
import { createGlobalState, useGlobalState } from 'rgstate';

// inspired by React.createContext
export const PostsState = createGlobalState([], { name: 'posts' });

export default function App() {
  // inspired by React.useState
  const [posts, setPosts] = useGlobalState(PostsState);

  useEffect(() => {
    const handleFetch = async () => {
      const result = await fetch('https://jsonplaceholder.typicode.com/posts');
      const data = await result.json();
      setPosts(data);
    };
    handleFetch();
  }, [setPosts]);

  return (
    <div>
      Fetched posts: {posts.length}
    </div>
  );
}

And that's all you need!


API

import {
    createGlobalState,
    useGlobalState,
    useGlobalSetter,
    useGlobalGetter
} from 'rgstate';
  • createGlobalState to initialize your global state
  • useGlobalState to get the [value, setter] variables
  • useGlobalSetter to get the static setter only
  • useGlobalGetter to get the reactive value only

createGlobalState

createGlobalState<T>(defaultValue: any, params: { name?: string; persist?: boolean }) => GlobalState<T>

  • Initialize RGState like React's context, using createGlobalState and providing a default value
import { createGlobalState } from 'rgstate';

export const PostsState = createGlobalState([]);

Custom name - Recommended 🚨

Provide an optional key name for the internal store. If you skip this, a new uuid will be generated when the global state initializes. This causes issues with application hot reload where you could lose your stored data during development if you don't provide a key name.

export const PostsState = createGlobalState([], { name: 'posts' });

Sync with local storage

If you want to store your last data shape in your browser storage, use the persist: true config option

export const PostsState = createGlobalState([], { persist: true });

useGlobalState

useGlobalState(GlobalState) => [value: T, setter: (handler: GlobalStateSetType<T>) => void]

  • Use it like React's state
  • the useGlobalState hook returns values provided by useGlobalGetter and useGlobalSetter
import React from 'react';
import { useGlobalState } from 'rgstate';

import { PostsState } from './state';

const App = () => {
  const [posts, setPosts] = useGlobalState(PostsState);
}

useGlobalSetter

useGlobalSetter(GlobalState) => (handler: GlobalStateSetType<T>) => void

  • In case you only need the setter and don't need the reactivity of the current value, opt in for using useGlobalSetter
  • The returned method doesn't re-create and therefore it's safe to use it as a useEffect or useCallback dependency
import React from 'react';
import { useGlobalState } from 'rgstate';

import { PostsState } from './state';

const PostDelete = () => {
  const setPosts = useGlobalSetter(PostsState);
}
  • The setter accepts
    • a value
    • a function, which provides you with the current value as a parameter, very similar to React's useState API
setPosts([{ id: 1, name: 'New Post' }])
setPosts((previousPosts) => {
    const newPosts = [...previousPosts]
    newPosts.slice(0, 1)
    return newPosts
})

useGlobalGetter

useGlobalGetter(GlobalState) => value: T

  • When you don't need the setter and are only concerned about the current reactive value, use useGlobalGetter
  • The returned value re-creates only when the value is directly changed and it's not affected by other global values changing
import React from 'react';
import { useGlobalGetter } from 'rgstate';

import { PostsState } from './state';

const PostDelete = () => {
  const posts = useGlobalGetter(PostsState);
}

As you introduce global states, global setters and global getters throughout your App, the values are stored in the same place. The setter accepts a function as a parameter and this function exposes the current value related to the setter as a parameter.

No matter how much you scale your app and how much global state properties you add, the implementation stays this simple.