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

@vighnesh153/react-use-global-state

v0.4.7

Published

A tiny global useState hook

Downloads

26

Readme

@vighnesh153/react-use-global-state

npm npm bundle size (scoped) npm (scoped) GitHub GitHub issues

A lightweight library (around 1KB minified), which allows you to create a global state using a ReactJS hook. The API of the hook is similar to the useState hook with minor differences.

Use this library as an alternative to popular state management solutions like Redux, MobX, etc. because you don't need to create any providers or action creators or any boilerplate code for creating a global state. You can even use this in place of the ReactJS's builtin Context API

Installation

npm install @vighnesh153/react-use-global-state

Usage

import { useGlobalState } from '@vighnesh153/react-use-global-state';

const Counter = ({ adder }) => {
  const [count, setCount] = useGlobalState('count', 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + adder)}>Add {adder}</button>
    </div>
  );
};

const App = () => {
  return (
    <div>
      {/** Count state will be same for all counters **/}
      <Counter adder={1} />
      <Counter adder={2} />
      <Counter adder={3} />
    </div>
  );
};

Cleaning up (in your tests)

To remove the global state from memory, you can make use of the forgetGlobalState function which will clean all the global pieces of state. It also accepts an array of identifiers (strings) to only forget those global state pieces.

import { forgetGlobalState } from '@vighnesh153/react-use-global-state';

describe('Your component tests', () => {
  // forgets all identifier states
  beforeEach(() => {
    forgetGlobalState();
  });

  // forgets those global state pieces that were marked with any one of these identifiers
  beforeEach(() => {
    forgetGlobalState(['counter', 'user', 'auth']);
  });
});

Performance

Any change in the state would just render the consumer components (and their children components) and not the entire application as you can see in the following example.

In the following example, we have the global render time in the <App /> component and all the counter cards are children of the <App /> component.

  • Adding a new counter re-renders the <App /> component because the logic of the count of counters is in the <App /> component
  • Adding 1 to any of the counters only re-renders the consumers of the count state (in this case, only the cards)

Counters Gif

Why you should use this library?

  • Size: 1KB minified
  • Zero external dependencies
  • Modern hook-based state management instead of the traditional redux-like, provider-consumer approaches
  • No need of wrapping components with a long chain of Providers as there is no Provider-Consumer pattern in this hook

Best practices

  • Try to keep the states very minimal. That way, to avoid re-rendering of big component trees with every minor change in the state
  • Although there is no restriction on how you want to use this, my recommendation would be to create a wrapper hook around you piece of state and add some utility functions in the hook to update the state. This lets you encapsulate your business logic for this piece of state in the hook, and you won't have to pass the identifier everytime as it will be done for you by the hook.
const useUser = (userId, initialValue) => {
  const [user, setUser] = useGlobalState(`user_${userId}`, initialValue || {});

  const changeName = useCallback(
    (newName) => {
      setUser({ ...user, name: newName });
    },
    [user]
  );

  const changeAge = useCallback(
    (newAge) => {
      setUser({ ...user, age: newAge });
    },
    [user]
  );

  return { user, changeName, changeAge };
};

How does this hook work?

  • This hooks makes use of the provided identifier to identify which global state you want to access.
  • When you change the state for an identifier, the new data gets published in a stream and all the components which are making use of the same identifier will get notified about the updates