dagda1
dagda1

Reputation: 28890

tips for moving logic out of componentDidUpdate

I have a redux connected component and I am using componentDidUpdate for a lot of logic and it is starting to get messy.

My componentDidUpdate looks a bit like this:

  componentDidUpdate(prevProps: Props) {
    if (this.props === prevProps) {
      return;
    }

    const {
      history,
      a,
      b,
      c
    } = this.props;

    if (!prevProps.a && !a) {
      this.proceedToNextStep();
      return;
    }

    if (b.length === b.length + 1) {
      history.push(rootUrl);
      return;
    }

    if (c != prevProps.c) {
      // do stuff
      return;
    }
  }

The props will change due to redux actions but I don't know a better place to determine where something has changed in the redux connected component.

This was perhaps wrong for one property but more logic is appearing in here and this is already messy.

Upvotes: 2

Views: 264

Answers (1)

Damien Leroux
Damien Leroux

Reputation: 11693

You can put your logic in:

  • componentWillReceiveProps(nextProps): this will at least avoid the componenent re-rendering before execute your component logic. The newProps will contains the props injected by Redux connect
  • mapsTateToProps: the Redux connect third parameter is a callback that is sent the merged props: (state props + dispatch props + own component props)
  • observables wrapped in Redux promise: This is for me the best option to handle logic because it doesn't involve React Components: I can chain js logic (with observables) and, at each step of the logic execution, I can trigger dispatch() and access the application Redux state. redux-observable module mixes both RxJS module (observables) and Redux promise module (redux promise) for easier uses.

Upvotes: 1

Related Questions