Skip to content

varld/use-state-global

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

A small hook for managing global state

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published