Core Concepts

At its core, Deviation is a Dependency Injection system. Its API consists of the following three components:

  • Store

  • Inject

  • Deviation

Every other features of Deviation is built around these three features.

Store

Store is a state container. It contains state, global variables and methods for manipulate these variables. It also has it own setState and life-cycle hooks, which is managed by Deviation.

import { Store } from 'deviation'

export class CounterStore extends Store {
    state = {
        counter: 0
    }
    
    increment = () => this.setState(({ counter }) => ({ counter: counter + 1 }))
    
    decrement = () => this.setState(({ counter }) => ({ counter: counter - 1 }))
}

Deviation

Deviation is a React component where we provide these stores to the components. It's a React component, put this component at the root of your project will provide the whole project with the stores we declared.

ReactDOM.render(
    <Deviation providers={[
        RouterService,
        LoginService,
        SignupService
    ]}>
        <AppRoot />
    </Deviation>,
    document.getElementById('root')
)

It initializes the stores, manage the stores life-cycle and injections order between stores and some further stuffs.

Inject

Last but not least, we need to inject these stores into the components that we use. Using Inject is the way we do that:

import { Inject } from 'deviation'

@Inject({
    routerService: RouterService,
    loginService: LoginService
})
export class LoginPage extends React.Component { }

We can also inject a store into a store. It is good to have a store that stands on top of another store and controls that store. It is how store architecture should be:

import { Inject } from 'deviation'

export class CounterStore extends Store {
    state = {
        counter: 0
    }

    increment() {
        this.setState(({ counter }) => ({ counter: counter + 1 }))
    }
}

@Inject({
    counterStore: CounterStore
})
export class TodoStore extends Store {
    state = {
        todos: []
    }
    
    addTodo(todo) {
        this.setState(({ todos }) => ({ todos: todos.concat([todo]) }))
        
        this.props.counterStore.increment()
    }
}

ReactDOM.render(
    <Deviation providers={[CounterStore, TodoStore]}>
        <AppRoot />
    </Deviation>,
    document.getElementById('root')
)

Last updated