sagen

Management global state with out provider

Usage no npm install needed!

<script type="module">
  import sagen from 'https://cdn.skypack.dev/sagen';
</script>

README

sagen Logo

Build Status Maintainability Test Coverage

min minzip dependency-count tree-shaking

Korean | English

⚙ How to install

npm

$ npm install --save sagen

yarn

$ yarn add sagen

🏃 Getting started

sagen is a state management library that uses a combination of individual repositories without root repositories.

1. Create a repository

You can create a store to manage the state. The store offers the following features:

-Detect changes in status when used in React -Combine multiple repositories to create one repository -Store management standardized with reducer and pattern -Store state comparison operation is managed to minimize the operation of unused state

1-a. createStore

You can display values that are not functions in store.

import { createStore } from 'sagen';

const numberStore = createStore(0);
const multipleStore = createStore({ num: 0, str: '' });

2. Status value management

The createStore function returns getState,setState functions.

In React, you can use useSagenStore, useSagenState, and useSetSagenState to manage values.

2-a. useSagenStore

The useSagenStore Hook returns getter and setter as an array.

The usage method is the same as the React.useState Hook.

Changes from other configurations can be received as getter.

import { createStore, useSagenStore } from 'sagen';

const store = createStore(0);

function Test() {
  const [num, setNum] = useSagenStore(store);
  
  const incrementNum = () => {
    setNum(curr => curr + 1);
  };
  
  return (
    <div>
      <p>num: {num}</p>
      <button onClick={incrementNum}>
        Increment
      </button>
    </div>
  );
}

2-b. useSagenState

useSagenState Hook returns getter of store.

import { createStore, useSagenState } from 'sagen';

const store = createStore(0);

function Test() {
  const num = useSagenState(store);

  return (
    <p>num: {num}</p>
  );
}

2-c. useSetSagenState

useSetSagenState Hook returns setter of store.

import { createStore, useSetSagenState } from 'sagen';

const store = createStore(0);

function Test() {
  const setNum = useSagenState(store);

  const incrementNum = () => {
    setNum(curr => curr + 1);
  };

  return (
    <button onClick={incrementNum}>
      Increment
    </button>
  );
}

2-1. getter

You can add arguments to useSagenStore and useSagenState that return getter.

This is used for performance optimization.

2-1-a. selector

You can pass selector to useSagenStore and useSagenState.

This is mainly used for object stores, and allows you to subscribe only to the desired value of the object values.

The subscribed value only affects getter, and setter has information about the original value.

Since sagen operates only on the values that the component subscribes to,

it is not recommended to subscribe to values that are not being used.

import { createStore, useSagenStore } from 'sagen';

const infoStore = createStore({
  name: 'jungpaeng',
  age: 22,
});

const ageSelector = store => store.age;

function Test() {
  // Pass the ageSelector as the component uses only the age value.
  const [age, setInfo] = useSagenStore(infoStore, ageSelector);

  const incrementAge = () => {
    setInfo(curr => ({ ...curr, age: curr.age + 1 }));
  };

  return (
    <div>
      <p>age: {age}</p>
      <button onClick={incrementAge}>
        Increment
      </button>
    </div>
  );
}
2-1-b. equalityFn

You can pass equalityFn to useSagenStore and useSagenState.

Used to detect if a component's subscribed value has changed.

Basically, === is used to compare, and shallowEqual is provided for comparing arrays, objects, etc.

import { createStore, useSagenStore, shallowEqual } from 'sagen';

const infoStore = createStore({
  name: 'jungpaeng',
  use: 'typescript',
  age: 22,
});

const selector = store => ({ name: store.name, age: store.age });

function Test() {
  // Even if the unsubscribed use value changes, the component does not react.
  const [info, setInfo] = useSagenStore(infoStore, selector, shallowEqual);

  const incrementAge = () => {
    setInfo(curr => ({ ...curr, age: curr.age + 1 }));
  };

  return (
    <div>
      <p>name: {info.name}</p>
      <p>age: {info.age}</p>
      <button onClick={incrementAge}>
        Increment
      </button>
    </div>
  );
}

3. redux

You can manage values by passing reducer.

3-a. pass to reducer

const store = createStore(0);
redux<{ type: 'increase' | 'decrease'; by?: number }>(
    store,
    (state, { type, by = 1 }) => {
        switch (type) {
            case 'increase':
                return state + by;
            case 'decrease':
                return state - by;
        }
    },
);

3-b. storeDispatch

The redux function returns dispatch.

const store = createStore(0);
const storeDispatch = redux<{ type: 'increase' | 'decrease'; by?: number }>(
    store,
    (state, { type, by = 1 }) => {
        switch (type) {
            case 'increase':
                return state + by;
            case 'decrease':
                return state - by;
        }
    },
);

storeDispatch({ type: 'increase' });

4. computed

You can get a computed value based on the state value.

const store = createStore({ a: 0, b: 0 });  // not use
const computedStore = computed(
    store,
    (state) => {
        return {
            ab: state.a + state.b
        };
    },
);

computedStore.setState({ a: 50, b: 100 });
computedStore.getState(); // { a: 50, b: 100 }
computedStore.getComputed(); // { ab: 150 }

4-a. useComputed

Use the useComputed Hook to get the computed value.

const store = computed(createStore({ a: 0, b: 0 }), (state) => state.a + state.b);
const [state, setState] = useSagenStore(store);
const computed = useComputed(store);

// state: { a: 0, b: 0 }
// computed: 0

4-b. useComputed with selector

You can pass selector and equalityFn as arguments to useComputed Hook.


const store = computed(createStore({ a: 0, b: 0 }), (state) => ({
    sum: state.a + state.b,
    isEnough: (state.a + state.b) > 100 ? 'enough' : 'not enough',
}));
const [state, setState] = useSagenStore(store);
const computed = useComputed(store, computed => computed.sum);

// state: { a: 0, b: 0 }
// computed: 0

5. Subscribe to events

You can trigger an event when an update occurs.

This event cannot affect the state value.

5-a. onSubscribe

import { createStore } from 'sagen';

const store = createStore(0);

// Returns a function that unsubscribes from event.
const removeEvent = store.onSubscribe((newState, prevState) => {
  console.log(`prev: ${prevState}, new: ${newState}`);
});

// In Component ...
const [state, setState] = useSagenStore(store);
setState(1);
// [console.log] prev: 0, new: 1

removeEvent();
setState(0);
// [console.log] Empty

6. Store merging

Multiple stores' can be combined and managed as a single store`.

If you wish, you can also create and manage a single Root Store.

Using without React

sagen can be used without React.

Try the sagen-core library.

📜 License

sagen is released under the MIT license.

Copyright (c) 2020 jungpaeng

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.