项目作者: IniZio

项目描述 :
🤔 Handle logic in frontend
高级语言: TypeScript
项目地址: git://github.com/IniZio/reim.git
创建时间: 2018-07-29T08:14:43Z
项目社区:https://github.com/IniZio/reim

开源协议:MIT License

下载


Iniz

Iniz is a reactive state library for ReactJS. Try it out on our website!

npm i @iniz/core

Build Status
Test Coverage
@iniz/core"">Build Size
@iniz/core"">Version
@iniz/core"">Downloads

Guide

Getting started

Create an atom / store

  1. import { atom, store } from "@iniz/core";
  2. const timer$ = atom(new Date());
  3. const nested$ = store({
  4. obj: {
  5. array: [{ count: 3 }],
  6. message: "Hello World",
  7. },
  8. async reset() {
  9. this.array = [];
  10. this.message = "Good bye";
  11. },
  12. });

Mutate the atom value

Call the atom to read/write it.

  1. // Initial value
  2. timer$(); // Returns latest value e.g. `2019-08-31T00:00:00.000Z`
  3. // Mutate the atom / state
  4. setInterval(() => {
  5. nested$.obj.array[0].count++;
  6. timer$(new Date());
  7. }, 1000);
  8. // Later on...
  9. timer$(); // Returns latest value e.g. `2022-08-31T00:00:00.000Z`
  10. nested$.obj.array[0].count;
  11. nested$.reset();

Subscribe to atom

Use effect() to subscribe to value change.

  1. const dispose = effect(() => {
  2. console.log("Updated timer: ", timer$());
  3. });
  4. // Execute `dispose` to stop effect
  5. dispose();

Use computed() to get calculated value from multiple atoms.

  1. const timerAndCounter$ = computed(
  2. () => `Computed: '${nestedCounter$().obj.array[0]}' '${timer$()}'`
  3. );
  4. timerAndCounter$(); // Returns "Computed: 2022-08-31T00:00:00.000Z 4"

React ⚛

npm i @iniz/react

@iniz/react already re-exports @iniz/core, so don’t need to install @iniz/core yourself

Simply use atom() values in components, they will re-render correctly thanks to useSyncExternalStore

  1. import { useAtom, useComputed } from "@iniz/react";
  2. // The component won't re-render when `nestedCounter$().obj.array[0].count` is updated
  3. function MessageInput() {
  4. // Equivalient to `atom()`
  5. const counter = useAtom(10);
  6. // Equivalent to `computed()`
  7. const computedCounter = useComputed(
  8. () => `Computed: ${nestedCounter$$().obj.message}`
  9. );
  10. // Equivalent to `effect()`
  11. // NOTE: You can also use `useEffect` with atoms actually
  12. useSideEffect(() => {
  13. console.log("[Latest message] ", computedCounter());
  14. });
  15. return (
  16. <div>
  17. <button onClick={() => counter(counter() + 1)}>{counter()}++</button>
  18. <input
  19. value={nestedCounter$().obj.message}
  20. onChange={(evt) => (nestedCounter$().obj.message = evt.target())}
  21. />
  22. </div>
  23. );
  24. }

Credits