Git Product home page Git Product logo

use-global-hook's Introduction

use-global-hook

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


Table of Contents

Install:

npm i use-global-hook

or

yarn add use-global-hook

Minimal example:

import React from 'react';
import globalHook from 'use-global-hook';

const initialState = {
  counter: 0,
};

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

const useGlobal = globalHook(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.


Map a subset of the global state before use it. The component will only re-render if the subset is updated.


Hooks can't be used inside a class component. We can create a Higher-Order Component that connects any class component with the state. With the connect() function, state and actions become props of the component.


Add Immer.js lib on your hook options to manage complex immutable states. Mutate a state draft inside a setState function. Immer will calculate the state diff and create a new immutable state object.


Using TypeScript

Install the TypeScript definitions from DefinitelyTyped

npm install @types/use-global-hook

Example implementation

import globalHook, { Store } from 'use-global-hook';

// Defining your own state and associated actions is required
type MyState = {
  value: string;
};

// Associated actions are what's expected to be returned from globalHook
type MyAssociatedActions = {
  setValue: (value: string) => void;
  otherAction: (other: boolean) => void;
};

// setValue will be returned by globalHook as setValue.bind(null, store)
// This is one reason we have to declare a separate associated actions type
const setValue = (
  store: Store<MyState, MyAssociatedActions>,
  value: string
) => {
  store.setState({ ...store.state, value });
  store.actions.otherAction(true);
};

const otherAction = (
  store: Store<MyState, MyAssociatedActions>,
  other: boolean
) => { /* cool stuff */ };

const initialState: MyState = {
  value: "myString"
};

// actions passed to globalHook do not need to be typed
const actions = {
  setValue,
  otherAction
};

const useGlobal = globalHook<MyState, MyAssociatedActions>(
  React,
  initialState,
  actions
);

// Usage
const [state, actions] = useGlobal<MyState, MyAssociatedActions>();

// Subset
const [value, setValue] = useGlobal<string, (value: string) => void>(
  (state: MyState) => state.value,
  (actions: MyAssociatedActions) => actions.setValue
);

// Without declaring type, useGlobal will return unknown
const [state, actions] = useGlobal(); // returns [unknown, unknown]

// Happy TypeScripting!

use-global-hook's People

Contributors

andregardi avatar bigles avatar nodtem66 avatar davityavryan avatar ojameso avatar subhendukundu avatar aliaksandr-s avatar david-westerman-dsg avatar lulusir avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.