The importance of using stateless components

Whenever you create a new React component, ask yourself whether this component will have any internal state. If that state is not immediately obvious, make it a stateless component (i.e. a function). Why?

Methods couples functions to your class

This is the most insidious drawback of stateful components (classes), since you easily fool yourself into thinking that all your methods will be pure functions. In reality I’ve found that the allure of simply referencing props and state directly from within the method is too strong. Your intentions are good but the environment is working against you. Take discipline and willpower out of the equation and stop using methods.

If you were using a stateless component to begin with, that decision would already have been made for you. You would be forced to create a pure function to add the functionality, thus decoupling it from the component.

The importance of this decoupling cannot be overstated. As your codebase grows the strong coupling of the class will make your classes grow, adding even more complexity. The friction involved in refactoring a tightly coupled method is significantly higher than accomplishing the same with a pure function. Again, the environment is working against you.

Pure functions also have the added benefit that they are easier to test and debug, since they only depend on their arguments and no external state.

Where’s the state?

A stateless component can’t hold any state (duh), but most interesting applications needs to deal with state somehow. Put it in a singleton and pass only the necessary state as props to your components. If you don’t like the smell of this god-object, use something like Redux, so you don’t have to repeat the design mistakes so many has suffered through before you. Redux gives you strong patterns that will help you decouple components from state with minimal work. In fact, I would recommend using Redux for anything that has more than a few fields of state.

Wrap up

I believe using stateless components and passing state as arguments is the most significant changes you can make in reducing future technical debt of your React applications. Using a state manager like Redux makes this easy.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.