Using recompose to make stateless, functional components work well with react-router 4.x

recompose is a higher order component toolkit for React. Like many other React developers, I use react-router. Unfortunately, I’ve been stuck using react-router 3.x for one simple reason — lifecycle.

I like my components pure. In react-router 3.x we had lifecycle methods baked into route declarations. I used these extensively, particularly the onEnter hook, but also onChange and onLeave hooks, to handle nifty things like telling a store to start fetching some data. Here’s an example of how these functions are declared in react-router 3.x.

react-router 3.x

Unfortunately, or maybe fortunately depending on what you like, react-router 4.x removed these lifecycle hooks completely, directing developers to use React component lifecycle methods instead.

So I kept react-router 3.x in production...

react-router 4.x and recompose

In steps recompose and the lifecycle higher-order component.

This pattern extends to other React lifecycle methods such as componentWillReceiveProps, which can be used to replace the onChange hook from react-router 3.x.

Full Example Component

Here we will use componentDidMount from the React component lifecycle along with setState. The lifecycle higher-order component will propagate any setState calls to the wrapped component as props. In our example component we’re going to assume the response is of the type{ "message": string } for a successful request and of type{ "error": string } on failure.

Takeaway

recompose may be the most useful library out there for working with stateless, functional components. The lifecycle higher-order component is just the beginning of what you can accomplish while keeping your components pure. Try out mapProps, withHandlers, the (literally) essential compose to get started.

I hope this story saves someone a few hours of work. Thanks for reading!