use-state-global
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

Use State Global

A really simple react hook for managing shared/global state.

About

Sometimes you might want to manage global application state but don't need something like Redux or Mobx. That's what useStateGlobal is for.

It seamlessly synchronizes state across all components that use it but does not increase your bundle size by that much.

Install

# yarn
yarn add use-state-global

# npm
npm install --save use-state-global

Usage

Basic Hook

import createGlobalState from 'use-state-global';

let useGlobalState = createGlobalState({
  // initial state
  count: 1
});

let Component = () => {
  let [state, setState] = useGlobalState();

  return (
    <div>
      Count: {count}
      <button onClick={() => setState({ count: count + 1 })}>Add 1</button>
    </div>
  );
};

let OtherComponent = () => {
  let [state] = useGlobalState();

  return <div>Same count as the other one: {count}</div>;
};

Accessing state from the outside

import createGlobalState from 'use-state-global';

let useGlobalState = createGlobalState({
  // initial state
  count: 1
});

// Set state from outside
useGlobalState.setState({ count: 5 });

// Get state from outside
console.log(useGlobalState.getState());
// > { count: 5 }

let Component = () => {
  let [state, setState] = useGlobalState();

  return (
    <div>
      Count: {count}
      <button onClick={() => setState({ count: count + 1 })}>Add 1</button>
    </div>
  );
};

License

MIT © Tobias Herber

Made by Varld

Readme

Keywords

none

Package Sidebar

Install

npm i use-state-global

Weekly Downloads

2

Version

0.2.0

License

MIT

Unpacked Size

14.5 kB

Total Files

15

Last publish

Collaborators

  • tobihrbr