The Strategy Design Pattern has been used by most seasoned object-oriented programmers for decades. It is one of the 23 “Gang of Four” design patterns.

But for most of us who are mere mortals, we have been using if-else and switch statements in our code, where the strategy pattern should be more appropriate.

I won’t even try to detail what the advantages of the Strategy Design Pattern are. There are many discussions out there that are just a Google search away. But allow me a simple demonstration.

The Obvious Way: If-Else and Switch

Say you wanted to build a React component which renders another component according to the state (either local or application state, but we’ll deal with local state in this sample).

If you were to implement it via if-else statements, the component may look something like this:

You may improve your renderComponent method with a switch statement like so:

Both techniques are well and good. But imagine a usage case when you may want to use ShowComponent to render one of a hundred possible components at any given time. You will end up with a hundred ifs or a hundred cases in your component. Well, you may argue that you can pull out the method into its own module and import it into your ShowComponent.

But let me propose another solution: let’s harness the power of the Strategy Design Pattern.

The Alternative Way: Introducing The Strategy Design Pattern

(Updated to reflect proper state implementation.)

The Strategy Design Pattern is kind of tricky to implement when it was first proposed in Java. Luckily for us, we have a tool in JavaScript that makes it a lot easier to implement the pattern: JavaScript Object Literals.

Now, look at how we may implement the ShowComponent React component:

Woah, what happened here? Notice that the renderSubComponent method now retrieves the property of a new object, called subComponents, based on current state.

Let’s take a look at the subComponents object (which we move into its own module):

The advantages may not seem obvious now. But as your application scales, the Strategy Design Pattern via JavaScript Object Literals will be pretty valuable. If used correctly, the pattern will make your code more maintainable and readable.

Did you like the pattern? Do you think you’d use it in your projects? Let me know by commenting below.

Working Sample

I know you are probably itching to see the pattern in the real world. I created a working demonstration on CodeSandbox for that purpose. Just navigate to https://codesandbox.io/s/6lv47n6pow.

2 thoughts on “Improve Your React Code with Strategy Design Pattern

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.