1.0.7 • Published 2 years ago

use-reactive-ts v1.0.7

Weekly downloads
-
License
-
Repository
github
Last release
2 years ago

npm npm GitHub Workflow Status npm bundle size npm bundle size

Use Reactive TS

React hook for having a mutable state that will be reactive without using setState. this hook is provided with TS first approach and performance consideration so it will not increase the number of your components renders.

UseReactive Simple Usage


Motivation

React is a treble name for the React lib, as it doesn't react to changes, we tell React, listen we had a change, there is our new state, please change it. But this is not native. Take a minute to think about why counter++ is not enough to place the new value on the screen. Now try to think of some production complex state cases where you had to loop and find an object and only then do something to it while you have the object in your hand in the first place! Why not just change it.

This approach is probably not the React/Functional way of handling state changes, but hey, this is more programing language native. Take Immer for an example, how easy it is just to change the object you are running on.

A highly recommended session by Rich Harris about how React is not reactive by its nature and how that inspired him to write Svelt.


How it works

To have all React side effects by rerendering a component, useReactive uses useState and useMemo to improve memoization. The following is a sequence diagram which describes the flow of actions to have a reactive state.

UseReactive Simple Usage


Installation

npm install use-reactive-ts --save

Signature

function useReactive<T extends object>(initialState: T): T;

Usage

Simple Counter

type CounterState = {
    counter: number;
};

const Counter = () => {
    let state = useReactive<CounterState>({ counter: 0 });

    if (state.counter > 5) {
        state.counter = 0;
    }

    return (
        <div>
            <div>
                counter: {state.counter}
                <button onClick={() => state.counter++}>counter +</button>
            </div>
        </div>
    );
};

Counter with nested object

type CounterInnerState = {
    inner: {
        counter: number;
    };
};

const Counter = () => {
    let state = useReactive<CounterInnerState>({ inner: { counter: 0 } });

    if (state.inner.counter > 5) {
        state.inner.counter = 0;
    }

    return (
        <div>
            <div>
                counter: {state.inner.counter}
                <button onClick={() => state.inner.counter++}>counter +</button>
            </div>
        </div>
    );
};

For more usage, check out Test Suits and Examples.

Sandbox


Test

  • Component is reactive by mutable state changes
  • Number of component renders
  • Number of complex components tree renders
npm test
1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago