tn-reactive-state

Class that creates a reactive state.

Usage no npm install needed!

<script type="module">
  import tnReactiveState from 'https://cdn.skypack.dev/tn-reactive-state';
</script>

README

Bundle Size - 1.45 Kb gzipped

new ReactiveState()

Class that creates a reactive state.

const state = new ReactiveState(value, defaultCallbackTimeout)
state.current = 1
console.log(state.current)

const handle = state.on(value => console.log(value), callbackTimeout)
handle.disconnect()
Properties Info
.id ReactiveState() instance id
.current Current state of ReactiveState()
.forceUpdate() Force callback to all listeners
.on( func, timeout ) Start listening to any update

useReactiveState()

React hook watches a ReactiveState and returns the value of it. And re-render the component when the state is changed.

const state = new ReactiveState(value)
const value = useReactiveState(state)

useReactiveUpdate()

React hook watches a ReactiveState and re-renders the react component when the state is changed

const state = new ReactiveState(value)
useReactiveUpdate(state)

useWatchReactiveState()

React hook watches one or more ReactiveStates and returns the value of 2nd parameter.

class Person {
  public firstName = new ReactiveState('')
  public lastName = new ReactiveState('')

  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

const person = new Person()
const fullname = useWatchReactiveState([person.firstName, person.last], person.fullName)

useReactiveStateAfterload()

In some rare condition there may be change in the state before establishment of react hook watcher when using useReactiveState() or useWatchReactiveState(). This hook will try to refresh the state if the state is already changed.

Below example will update the component only when the state is changed

const loading = useReactiveState(classable.loading)
useReactiveStateAfterload([classable.loading, loading])

Below example will always update afterload

const loading = useReactiveState(classable.loading)
useReactiveStateAfterload()