State and Lifecycle

In Deviation, store has two life-cycle hooks and one object member called notifier:

  • storeDidMount

  • storeWillUnmount

  • notifier

setState

Unlike React, Deviation setState is synchronous. It's because a store doesn't have any render method. It should not rely on any dependent component either. So this way, store is much more lightweight and predictable when being used with React.

storeDidMount and storeWillUnmount

As it name,storeDidMountis called whenever the store is mounted to a Deviation including re- initialization or re-injection. Similarly, storeWillUnmount is called whenever the store is unmounted from a Deviation or it's removed from the Deviation somehow.

Notice:

  • Every computations and side-effects should take place inside storeDidMount. Store constructor should be as lightweight as possible to avoid errors and deadlocks.

notifier

Deviation at its very own core use RxJS Subject to notify components about state changes. As we said unlike React, Deviation don't have storeDidUpdate because its setState is synchronous and storeDidUpdate is inefficient for performance concern. Instead, to get notification about state change from store to store, you can use notifier.

import { notifier } from 'deviation'

@Inject({
    counterStore: CounterStore
})
export const TodoStore extends Store {
    storeDidMount() {
        this.subscription =
            this
                .props
                .counterStore[notifier]
                .subscribe((prevState) => { })
    }
    
    storeWillUnmount() {
        this.subscription.unsubscribe()
    }
}

It is worth to say that, the state you get from the notifier is not the latest state but the previous state. This is because the state is modified directly inside the store, so it will act like what componentDidUpdate do, dispatch the previous state to the listeners for further computations.

Last updated