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

use-global-hook

v0.3.0

Published

Easy state management for react using hooks in less than 1kb.

Downloads

22,066

Readme

use-global-hook

Easy state management for react using hooks in less than 1kb.


Table of Contents

Install:

npm i use-global-hook

or

yarn add use-global-hook

Minimal example:

import React from 'react';
import globalHook from 'use-global-hook';

const initialState = {
  counter: 0,
};

const actions = {
  addToCounter: (store, amount) => {
    const newCounterValue = store.state.counter + amount;
    store.setState({ counter: newCounterValue });
  },
};

const useGlobal = globalHook(initialState, actions);

const App = () => {
  const [globalState, globalActions] = useGlobal();
  return (
    <div>
      <p>
        counter:
        {globalState.counter}
      </p>
      <button type="button" onClick={() => globalActions.addToCounter(1)}>
        +1 to global
      </button>
    </div>
  );
};

export default App;

Complete examples:

Several counters, one value

Add as many counters as you want, it will all share the same global value. Every time one counter add 1 to the global value, all counters will render. The parent component won't render again.


Asynchronous ajax requests

Search GitHub repos by username. Handle the ajax request asynchronously with async/await. Update the requests counter on every search.


Avoid unnecessary renders

Map a subset of the global state before use it. The component will only re-render if the subset is updated.


Connecting to a class component

Hooks can't be used inside a class component. We can create a Higher-Order Component that connects any class component with the state. With the connect() function, state and actions become props of the component.


Immutable state with Immer.js integration

Add Immer.js lib on your hook options to manage complex immutable states. Mutate a state draft inside a setState function. Immer will calculate the state diff and create a new immutable state object.


Using TypeScript

Install the TypeScript definitions from DefinitelyTyped

npm install @types/use-global-hook

Example implementation

import globalHook, { Store } from 'use-global-hook';

// Defining your own state and associated actions is required
type MyState = {
  value: string;
};

// Associated actions are what's expected to be returned from globalHook
type MyAssociatedActions = {
  setValue: (value: string) => void;
  otherAction: (other: boolean) => void;
};

// setValue will be returned by globalHook as setValue.bind(null, store)
// This is one reason we have to declare a separate associated actions type
const setValue = (
  store: Store<MyState, MyAssociatedActions>,
  value: string
) => {
  store.setState({ ...store.state, value });
  store.actions.otherAction(true);
};

const otherAction = (
  store: Store<MyState, MyAssociatedActions>,
  other: boolean
) => { /* cool stuff */ };

const initialState: MyState = {
  value: "myString"
};

// actions passed to globalHook do not need to be typed
const actions = {
  setValue,
  otherAction
};

const useGlobal = globalHook<MyState, MyAssociatedActions>(
  initialState,
  actions
);

// Usage
const [state, actions] = useGlobal<MyState, MyAssociatedActions>();

// Subset
const [value, setValue] = useGlobal<string, (value: string) => void>(
  (state: MyState) => state.value,
  (actions: MyAssociatedActions) => actions.setValue
);

// Without declaring type, useGlobal will return unknown
const [state, actions] = useGlobal(); // returns [unknown, unknown]

// Happy TypeScripting!