DEV Community

El Marshall (she/they)
El Marshall (she/they)

Posted on

Redux and Higher Order Components

As I've mentioned in previous posts, I taught myself the quick and dirty of Redux to use it for my Flatiron final project, The World Builder's Tome. There are a few stories I could tell about that experience, but here I just wanted to go over one little mystery I ran into and the solution I found.

For Tome I was using Higher Order Components (HOCs) to manage authorization. This meant wrapping each React component that I wanted hidden behind the auth check in the authorization HOC. Here's what this looks like on the SearchPage component in one of my other projects:

export default PrivacyHOC(SearchPage);

Now, here's the thing. Redux works very similarly. Here's the export line on the Login Page component for Tome, where Redux is in play but not the authorization HOC:

export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginPage);

As you can see, both essentially involve wrapping the exported component in something higher up. So I ran into an issue. For the majority of the pages throughout Tome, I needed both. The Auth HOC would need to be wrapped, as well as the base level component. My initial reaction was of course, What the heck is that supposed to look like??? (I was rather stressed at the time.) The layering was mind bendy.

So I did a little digging. I poked around online and found the answer I needed in a Stack Overflow response, which I have not been able to locate again, or I would link it here.

The key, as it turns out, was very simple. There is something you can do called "composing" that essentially combines the components for you.

Here is the code from my AuthHOC component:

import React from "react";
import { Redirect } from "react-router-dom";
import { connect } from "react-redux";
import {compose} from 'redux'

const AuthHOC = WrappedComponent => {
…
};

const mapStateToProps = state => {
…
};


const composedAuthHOC = compose(
connect(mapStateToProps), AuthHOC
)
export default composedAuthHOC;

Using 'compose,' I was able to simply export this new 'composedAuthHOC' component for use elsewhere instead of the simpler AuthHOC which did not have access to state. This meant that wherever I wanted to both use the AuthHOC and reference the redux state later on, I could put this in the export statement of a component:

export default connect(
mapStateToProps,
mapDispatchToProps
)(composedAuthHOC(EditForm));

Tada! Clean and simple. Solved my problem, anyway.

Alright it is late and I am way more tired than I thought I was. I hope this was at all coherent, hah!

Top comments (0)