JSPM

  • Created
  • Published
  • Downloads 47
  • Score
    100M100P100Q60776F
  • License MIT

Hook-based global state for React

Package Exports

  • @dr.pogodin/react-global-state

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@dr.pogodin/react-global-state) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Dr. Pogodin's React Global State

Efficient and simple to use global state management for React, implemented with hooks, and spiced by useful data management functions (async retrieval, caching, etc.).

Content

/**
 * Base example: ComponentA and ComponentB rely on the same value in the global
 * state. Clicks of the button inside ComponentB update the value rendered by
 * ComponentA.
 */

import React from 'react';
import {
  GlobalStateProvider,
  useGlobalState,
} from '@dr.pogodin/react-global-state';

function ComponentA() {
  const [value] = useGlobalState('some.state.path', 0);
  return <div>Component A: {value}</div>;
}

function ComponentB() {
  const [value, setValue] = useGlobalState('some.state.path', 0);
  return (
    <div>
      <button onClick={() => setValue(value + 1)}>
        &uArr; Bump!
      </button>
    </div>
  );
}

export default function Demo() {
  return (
    <GlobalStateProvider>
      <ComponentA />
      <ComponentB />
    </GlobalStateProvider>
  );
}

Reference

  • <GlobalStateProvider /> – Provides global state to its children. The Missing GlobalStateProvider error is thrown if a library function is used inside a component which cannot find a provider up in the component hierarchy. Multiple providers can be used, and nested, in the same code. In such case a component will see the global state from the closest provider up in the component hierarchy.

    Children are optional, and they are rendered at the component place.

    Properties

    • [initialState] (Any) – Optional. Initial global state.
  • useGlobalState(path, [initialValue]) – Base global state hook, similar to React's useState hook for the local state. It subscribes the component to the data located at the given state path, and also exposes the data update method.

    Arguments

    • path (String) – State path. It can be undefined to subscribe for entire state, though for most practical applications components should subscribe for relevant state paths.

      Internally, the state is a single object, and data are read and written to paths using lodash's _.get(..) and _.set(..) methods. Thus, it is safe to read, and set paths which have not been set in the state yet.

    • [initialValue] (Any) – Optional. Initial value. If given, it will be set at the path, if the current value at the path is undefined.

    Returns [value, setValue(newValue)] – Array with two elements. The first one is the value at the path. The second one is the function to update the path value.

  • useAsyncData(path, loader, [options]) – Hook for storing async data in the global state and the specified path. When different components in your application rely on the same async data (e.g. fetched from a remote API), this hook simplifies loading, and reusing these data among the components (i.e. load just once, refresh if stale, etc.)

    Given async data loader (a function which returns a Promise resolving to some data), this hook loads data to the specified global state path, ensuring that loader is triggered a single time even if the hook is called from different components (it is assumed that all calls of useAsyncData(..) for the same path rely on the same loader). It remembers the timestamp of data retrieval, and the number of components relying on the data. If hook is used when data are already present in the state, it reloads the data only if existing ones are older than the specified maximum age. It clears stale data from the state, when the last component relying on them is dismounted.

    Arguments

    • path (String) – State path, where all related information will be kept.
    • loader (Function) – Async function with resolves to the data of interest.
    • [options] (Object) – Optional. Additional parameters.
      • [options.maxage] (Number) – Optional. Maximum age of data acceptable to the caller. If data in the state are older than this time [ms], the reloading will be initiated.

    Returns object with the following fields:

    • data (Any) – current data stored at the state.
    • loading (Boolean) – true if the data are being loaded.
    • timestamp (Number) – Timestamp of the data currently loaded into the state [ms]. Defaults 5 min.

Notes

P.S.: Mind the version 0.0.1. As of now it is a proof-of-concept, which works great in the few tests I did. If you try, and find glitches, please report the bugs, it will help to polish this library faster.