@znemz/use-global-hook
TypeScript icon, indicating that this package has built-in type declarations

1.1.9 • Public • Published

@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:

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.

setRef vs setState

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

Readme

Keywords

none

Package Sidebar

Install

npm i @znemz/use-global-hook

Weekly Downloads

1

Version

1.1.9

License

ISC

Unpacked Size

31.9 kB

Total Files

12

Last publish

Collaborators

  • stevenheinrich
  • nmccready