/use-global-hook

Easy application state management for react.

Primary LanguageTypeScript

@znemz/use-global-hook NPM version build status Test coverage

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


Minimal example:

import React from 'react';
import useGlobalHook from '@znemz/use-global-hook';

const initialState = {
  counter: 0,
};

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

const useGlobal = useGlobalHook({ React, 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:

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.


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

Sometimes you just need to set a reference and wipe the state clean.

There are many use cases:

  • reset / wipe
  • tracking dom elements ref={setRef}

Why do we allow React Injection?

  • to support different React implementation
  • to allow different versions of useEffect, useState or other hooks
    • say to allow inspection for redux-devtools see reinspect to debug your global hooks