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

global-hook-store

v1.0.3

Published

A React hook for using global store with hooks

Downloads

62

Readme

global-hook-store

build

Dead simple global store using hooks for react.

Demo

TL;DR

Counter: https://codesandbox.io/s/j2v0p6kq7w

Todo list: https://codesandbox.io/s/54kwqpppnx

Installation

// yarn
yarn add global-hook-store

// npm
npm -i global-hook-store --save

Usage

Its super super simple to use. Only three steps required.

  1. Create your store with initial state & reducer style functions 👇
const counterStore = createStore(
  {
    count: 0,
  },
  {
    increment: ({ count }) => ({ count: count + 1 }),
    decrement: ({ count }) => ({ count: count - 1 }),
  }
);
  1. Use store 👌
const App = () => {
  const { actions, state } = useStore(counterStore);

  return (
    <>
      <h1>Count {state.count}</h1>
      <button onClick={() => actions.decrement()}>-</button>
      <button onClick={() => actions.increment()}>+</button>
    </>
  );
};
  1. Profit 🎉

The reducer style functions are converted to actions which could be called from react

Example with payload

Todo list:



const todoStore = createStore({} as Todo, {
  // payload is here:  👇
  toggleTodo: (todos, todo:string) => {
    todos[todo] = !todos[todo];
    return { ...todos };
  },
  // payload is here:👇
  addTodo: (todos, input:HTMLInputElement) => {
    const todo = input.value;
    input.value = "";
    return { ...todos, [todo]: false };
  }
});
const ToDoList = () => {
  const { state, actions } = useStore(todoStore);
  const ref = useRef(null);

  return (
    <div>
      <h3>Todo list example</h3>
      {Object.entries(state).map(([todo, done], i) => (
        // passed payload:                      👇
        <div onClick={() => actions.toggleTodo(todo)} key={i + todo}>
          {todo}
          {done ? " ✔" : " ⏲"}
        </div>
      ))}
      <input ref={ref} />
      <button onClick={() => actions.addTodo(ref.current!)}>Add todo</button>
    </div>
  );
};

Nice to have

Typescript support

When using typescript actions, state and payload types are infered: Infered Types

If you dont need any payload, simply don't specify it in the reducer or set the payload type as null or undefined and the mapped actions could be executed like this:

const fooBarStore = createStore(
  {
    fooBar: 0
  },
  {
    setFooBar: (_state, payload:number) => ({ fooBar: payload }),
    incrementFooBar: ({fooBar}) => ({ fooBar: fooBar + 1 })
    decrementFooBar: ({fooBar},payload:null) => ({ fooBar: fooBar - 1 })
  }
)
fooBarStore.actions.setFooBar(10);
fooBarStore.actions.incrementFooBar();
fooBarStore.actions.decrementFooBar();

fooBarStore.actions.setFooBar(); // error, because we are missing required payload

Async actions work out of the box:

const counterStore = createStore(
  {
    count: 0,
  },
  {
    increment: ({ count }) => ({ count: count + 1 }),
    decrement: ({ count }) => ({ count: count - 1 }),
    incrementByTen: async ({ count }) => {
      const promise = new Promise((resolve) => setTimeout(resolve, 3000));
      await promise;
      return { count: count + 10 };
    },
  }
);

Also use this handy util for automatically setting loading, error and data state:

const githubStore = createStore(
  {
    // async initialicer:👇 (will create a typed object like this { loading: false, data: [], error: undefined})
    repos: asyncState<Repo[]>([]),
    userId: ""
  },
  {
    setRepoId: (state, userId: string) => ({ ...state, userId }),
      // util function:                              👇
    getUserRepos: async ({ userId }, _payload, { asyncAction }) =>
      asyncAction("repos", githubApi.getRepo(userId))
  }
);

State receiver when using async actions

If you are modiyfing state within an async action you have to take state changes which may occur during your async action into consideration.

Consider the following store. If the incrementByTen action is called 3 times in less than one second (the time it takes to complete), the count will still be 10. Why? Because the moment when you call the action it will return the original states count which is 0 for each of those times. This is sometimes a common misstake, but its very simple to avoid.

const counterStore = createStore(
  {
    count: 0,
  },
  {
    increment: ({ count }) => ({ count: count + 1 }),
    incrementByTen: async ({ count }) => {
      await delay(1000);
      return { count: count + 10 };
    },
  }
);

//inside component:
for (let i = 0; i < 3; i++) {
  incrementByTen();
}

Solution:

You could use a "state receiver" from utils. The state receiver always returns the current state when called:

const store = createStore(
  {
    count: 0,
  },
  {
    increment: ({ count }) => ({ count: count + 1 }),

    incrementByTenReceived: async (_state, _payload, { receiveState }) => {
      await delay(1000);
      return { count: receiveState().count + 10 };
    },
  }
);

OR you can always await the state change by awaiting the action:

for (let i = 0; i < 3; i++) {
  await incrementByTen();
}

Getters and setters are preserved:

const nameAndCounterStore = createStore(
  {
    count: 0,
    name: "Willy wonka",
    get length() {
      return this.name.length;
    },
  },
  {
    increment: ({ count, ...state }) => ({ ...state, count: count + 1 }),
    decrement: ({ count, ...state }) => ({ ...state, count: count - 1 }),
    updateName: (state, name) => ({ ...state, name }),
  }
);
const {
  state: { length },
  actions,
} = useStore(nameAndCounterStore);
<span>{length}</span>

Use the same style local store also

const App = () => {
  const { actions, state } = useLocalStore(counterStore);

  return (
    <>
      <h1>Count {state.count}</h1>
      <button onClick={() => actions.decrement()}>-</button>
      <button onClick={() => actions.increment()}>+</button>
    </>
  );
};

Reset util

Use this util to reset the entire state to initial state or just a part of the state

const githubStore = createStore(
  {
    repos: asyncState<Repo[]>([]),
    userId: ""
  },
  {
    resetAll: (_state, _payload: null, { reset }) => reset(),
    resetRepos: (_state, _payload: null, { reset }) => reset("repos") // also typed
  }
);

Also available as a reset hook when componet unmounts. This is very practical for when having a "current" item present in the store. If you have a userStore for instance you might want the currentUser to be cleared when the user-details component is unmounted. useStoreReset will reset the stores key to its initial state when component is unmounted

useStoreReset(userStore, "currentUser");
useStoreReset(store, "stateKey1","stateKey2", "stateKey3"...)