DEV Community

Sivantha Paranavithana
Sivantha Paranavithana

Posted on • Updated on

What is stateful logic sharing and why do we need it?

Stateful logic is any code that uses the state. The stateful logic sharing is sharing stateful logic between multiple react components.

I believe the best way to understand this is with an example.

Let's say you want to create a component which has a button that increments a counter on click. We can implement that using a class component as below.

This will result a view like this, the counter increments with each button click.

Button counter

Now, let's say we want another component which increments a counter on hover over a div. We can implement that using a class component as below.

This will result a view like this. The counter increments when the mouse is hovered over the div.

Hover counter

Now, let's say we want another component which increments a counter on each key press. We can implement that using a class component as below.

This will result a view like this. The counter increments on each keypress.

Input counter

Now, let's backup for a minute. We can see that, in each of these scenarios we duplicated some logic. Specifically this part,

constructor(props) {
    super(props);

    this.state = {
        count: 0,
    };
}

increment = () => {
    this.setState((prevState) => ({ count: prevState.count + 1 }));
};
Enter fullscreen mode Exit fullscreen mode

This part uses the component's local state, therefore this is a stateful logic. And in each component it stayed basically the same, since the logic is the same.

Although in this example we only had to duplicate a simple few lines of code, this situation can occur in more complex scenarios as well.

So, how can we avoid this duplication?

The immediate thought (At least in my mind😉) is to "lift the state up".

We can declare the state and the increment handler in the parent component and pass down the state and the handler to children as props.

But this can be done only when we can create the same parent for the children. If the components are scattered throughout the react component tree, lifting the state up is not gonna be the current solution,

In that case, we need another solution to share this stateful logic between each component to avoid duplication.

That's where HOCs (Higher Order Components) and render props comes into the rescue. We will discuss about HOCs and render props in the upcoming articles.

Oldest comments (0)