React State-Transform Pattern

The Problem

When working with React, one issue I’ve run into is the reusability of certain functionalities in my React Components, but I’ve found that something feels a little weird to be:

class StateMicroChangeComponent extends React.Component {
    ...
    handleSelectCategory(selectedCategory) {
        let allResults = this.state.allResults;

        let filteredResults = this.filterResults(allResults, selectedCategory);
        filteredResults = this.sortResults(filteredResults);

        this.setState({
            filteredResults,
            selectedCategory,
        });
    }
    ...
}

In the above example, I’m happy if there’s only one instance where we perform the filtering/sorting, but if our Component performs these tasks multiple times, it might be difficult to maintain. If the implementation of the filter and sort change, we would need to update all the instances.

What I’ve Started Doing

With the amount of Redux I’ve been using recently, I’ve gotten used to the idea of transforming state as a whole, and applying reducers to it, resulting in more of a state-as-a-whole approach:

class StateTransformComponent extends React.Component {
    ...
    handleSelectCategory(selectedCategory) {
        let state = { ...this.state, selectedCategory };

        state = this.applyResultFilter(state);
        state = this.applyResultSort(state);

        this.setState(state);
    }
    ...
}

Now, if filtering or sorting need a tweak, the applyResultFilter and applyResultSort can contain the specifics, while the components interfaces with the transform function.

This has helped me a few times to simplify my code’s logic, even to the point of defining further functions that I would reuse like applyResultFilterAndSort which does both, for added reusability.

Written by Guillaume VanderEst