Getting Started

In this chapter, we will show you the usage of the library by adding Deviation to the example Counter App.

Create a Counter App

To create a counter app, first we will create a CounterApp that hold the Counter component:

CounterApp.tsx
import { Counter } from './Counter'

export class CounterApp extends React.Component {
    render() {
        return (
            <Counter />
        )
    }
}

And then we create the Counter component that render the counter and hold the counter state:

Counter.tsx
export class Counter extends React.Component {
    state = {
        counter: 0
    }
    
    decrement = () => {
        this.setState(({ counter }) => ({ counter: counter - 1 }))
    }
    
    increment = () => {
        this.setState(({ counter }) => ({ counter: counter + 1 }))
    }
    
    render() {
        return (
            <div>
                <p>Counter: <b>{this.state.counter}</b></p>
                <button onClick={this.decrement}>Decrement</button>
                <button onClick={this.increment}>Increment</button> 
           </div>
        )
    }
}

Now, we can mount the CounterApp to ReactDOM so that the counter app can run:

Lift the State Up

It's simple to create a CounterApp with a single state, but when you have to share the state throughout your app, you will need to Lift the State Up. To do that, we will create a CounterStore that handle store's state and actions:

Then, we need to add the CounterStore to the provider so that it will initialize and provide the Store throughout your app:

Now, CounterStore can be access anywhere in our app. We can now lift the state up by removing the component state and replace it with the state and the actions from CounterStore:

Last updated

Was this helpful?