DEV Community

loading...

Best way to handle lots of logic inside React Class Components

davidarmendariz profile image David Armendáriz ・1 min read

Context

We have a (very huge) application where sometimes there are files with 1000+ lines of code. What makes these files big are the logic of some methods. Wether we have too much logic on our component or not is not something I would like to discuss, at the end of the day, this is a production app and we have limited resources and limited time, so we need to find the best way to optimize the codebase while meeting deadlines (welcome to the real world!).

For example, suppose I have something like this:

class MyComponent extends Component {
    constructor() {
        // Lots of bindings
    }

    myHugeMethod1() {
        // Lots of logic that depends on this.props and probably other (hopefully smaller) class methods
    }

    myHugeMethod2() {
        // Lots of logic that depends on this.props and probably other (hopefully smaller) class methods
    }

    render() {
        // the render
    }
  }
Enter fullscreen mode Exit fullscreen mode

Our approach

We have obviously thought about lots of things: utility functions, static methods and classes with a single method. I personally find the last one the best approach. And this is what we have agreed to be the best approach (although we are not 100% sure):

import MyHelperMethod1 from "./MyHelperMethod1";
import MyHelperMethod2 from "./MyHelperMethod2";

class MyComponent extends Component {
    constructor() {
        // Lots of bindings
        const myHelperMethod1 = new myHelperMethod1(fixedProperties);
        const myHelperMethod2 = new myHelperMethod2(fixedProperties);
    }

    myHugeMethod1() {
        myHelperMethod1.setVariableProperties(variableProperties)
        myHelperMethod1.help()
    }

    myHugeMethod2() {
        myHelperMethod2.setVariableProperties(variableProperties)
        myHelperMethod2.help()
    }

    render() {
        // the render
    }
  }
Enter fullscreen mode Exit fullscreen mode

The variableProperties variable is probably an object. And probably this.props is going to be included inside of this object. It can feel odd, but that's how I do it.

How do you do it?

I want to hear about your approaches to handle these situations.

Discussion (0)

Forem Open with the Forem app