0

Most of the react application I've seen are organized with components that, in my opinion, do too much.

They may follow this pattern:

class MyComponent extends Component {

    constructor() {
        this.prop1 = this.props.prop1;
        this.prop2 = this.props.prop2;
    }

    render() {
        //....
    }

    onEvent(e) {
        this.setState({
            prop1: getProp1(),
            prop2: this.prop2() 
        });
    }
}

Personally in most cases I would prefer to avoid managing the state through React, and to have an object that does this. A possible solution would be something similar to:

class MyState {

    update(params) {
        this.prop1 = getProp1();
    }

}


class MyComponent extends Component {

    constructor() {
        this.state.obj = this.props.obj; // this has type MyState
    }

    render() {
        //....
    }

    onEvent(e) {
        this.obj.update(e.something);
        this.setState(this.obj);
    }
}

Since I've never seen this pattern used, and I'm not sure if using the same object as a prop and for the state, I wondering if I am missing something here.

Is this idea bad for some reason? Is there a better solution to manage the component state (as a whole, or just a subset) in a dedicated object?

  • Sounds like you want MobX. – JW01 Jan 16 at 16:12
  • I know that redux and mobX offer alternative solution to the state problem, and I know that when the app complexity grows they become almost a necessity, but I still feel that in some smaller applications a simple state-managing pattern may be a better solution. – heapOverflow Jan 16 at 16:36
  • I would agree if one was built into React, but I think you may be better off going with a known solution like MobX. It's actually pretty simple once you get the hang of it, and not too far from what you're trying to do. – JW01 Jan 16 at 17:02

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.