Developer Docs

MobX React State management

MobX is a JavaScript library for controlling state, while the previously explored patterns can be used for any custom React components, it is important to understand MobX state management because it is used consistently throughout C#Bot. MobX works by defining observer classes, observable variables and actions using decorator syntax (though this is not strictly required, it is simpler).

The @observer decorator is used at the top of the class and describes the component as using MobX to manage state. The @observable decorator is used above a variable to declare it as being managed by MobX.

import { action, observable } from "mobx";
import { observer } from "mobx-react";
import React, { Component } from "react";

@observer
export default class PersonInfo extends Component {
    constructor(props: any) {
        super(props);
    }

    @observable
    private name: string = "";

    @action
    handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
        this.name = e.target.value;
    };

    render() {
        return (
            <>
                <div>
                    <p>Entered Name: {this.name}</p>
                    <input
                        type="text"
                        onChange={this.handleInput}
                    />
                </div>
            </>
        );
    }
}

To change state we only need to call the handleInput function and because it has the @action decorator, MobX will intelligently realise this function is updating state and will act accordingly. If each of these decorators are omitted MobX will not understand how to correctly manage the state of your component and will not function as expected.

If you would like more information on MobX, please refer to our Introduction to MobX.

Was this article helpful?

Thanks for your feedback!

If you would like to tell us more, please click on the link below to send us a message with more details.

Tool:

Generate

Iterate

Bot:

C#Bot

SpringBot

On this page

New to Codebots?

We know our software can be complicated, so we are always happy to have a chat if you have any questions.