What is recompose?
Recompose is a React utility belt for function components and higher-order components (HOCs). It provides a set of helper functions to simplify the process of writing and managing HOCs, making it easier to enhance and compose components in a more declarative and functional style.
What are recompose's main functionalities?
withState
The `withState` HOC adds state to a functional component. In this example, it adds a `counter` state and a `setCounter` function to the `Counter` component.
const enhance = withState('counter', 'setCounter', 0);
const Counter = enhance(({ counter, setCounter }) => (
<div>
<p>{counter}</p>
<button onClick={() => setCounter(counter + 1)}>Increment</button>
</div>
));
withHandlers
The `withHandlers` HOC allows you to create handler functions that can be passed as props to the component. In this example, it creates an `onClick` handler that increments the `counter` state.
const enhance = withHandlers({
onClick: ({ counter, setCounter }) => () => setCounter(counter + 1)
});
const Counter = enhance(({ counter, onClick }) => (
<div>
<p>{counter}</p>
<button onClick={onClick}>Increment</button>
</div>
));
compose
The `compose` function allows you to combine multiple HOCs into a single HOC. In this example, it combines `withState` and `withHandlers` to create an enhanced `Counter` component.
const enhance = compose(
withState('counter', 'setCounter', 0),
withHandlers({
onClick: ({ counter, setCounter }) => () => setCounter(counter + 1)
})
);
const Counter = enhance(({ counter, onClick }) => (
<div>
<p>{counter}</p>
<button onClick={onClick}>Increment</button>
</div>
));
branch
The `branch` HOC conditionally applies an HOC based on a predicate function. In this example, it renders a loading component if `isLoading` is true, otherwise it renders `MyComponent`.
const enhance = branch(
({ isLoading }) => isLoading,
renderComponent(() => <div>Loading...</div>)
);
const MyComponent = enhance(({ data }) => (
<div>{data}</div>
));
renderNothing
The `renderNothing` HOC renders nothing if the predicate function returns true. In this example, it renders nothing if `shouldRender` is false.
const enhance = branch(
({ shouldRender }) => !shouldRender,
renderNothing
);
const MyComponent = enhance(({ data }) => (
<div>{data}</div>
));
Other packages similar to recompose
react-hooks
React Hooks provide a way to use state and other React features without writing a class. They offer similar functionality to Recompose but are built into React itself, making them more integrated and easier to use in modern React applications.
redux
Redux is a state management library for JavaScript applications. While it is more complex and powerful than Recompose, it can be used to manage state and side effects in a way that complements React components.
mobx
MobX is a state management library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). It offers a different approach to state management compared to Recompose, focusing on observables and reactions.
react-redux
React-Redux is the official React binding for Redux. It provides a way to connect React components to a Redux store, offering a more structured approach to state management compared to Recompose.
Recompose
Recompose is a microcomponentization toolkit for React. Think of it like lodash, but for React components.
npm install recompose --save
Documentation is a work-in-progress. Feedback is welcome and encouraged. If you'd like to collaborate on this project, let me know.
Quick example: Counter
Here's an example of a stateful counter component created using only pure functions and Recompose:
import { compose, withState, mapProps } from 'recompose';
const Counter = ({ counter, increment, decrement }) => (
<p>
Count: {counter}
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</p>
);
const CounterContainer = compose(
withState('counter', 'setCounter', 0),
mapProps(({ setCounter, ...rest }) => ({
increment: () => setCounter(n => n + 1),
decrement: () => setCounter(n => n - 1),
...rest
}))
)(Counter);
More complex examples are coming soon. Here's a mini React Redux clone from the test suite.
Read on for more about the library, its goals, and how it works.
API docs
Read them here
Usage
All functions are available on the top-level export.
import { compose, mapProps, withState } from 'recompose';
Optimizing bundle size
The total gzipped size of the entire library is 9.01 kB. You can reduce this number by only including the modules that you need.
All top-level exports can be imported individually:
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import withState from 'recompose/withState';
This is a good option for library authors who don't want to bloat their bundle sizes.
Recompose includes some lodash modules, like curry
and compose
, as dependencies. If you're already using lodash, then the net bundle increase from using Recompose will be even smaller.
Background
What is microcomponentization all about?
Forget ES6 classes vs. createClass()
. React 0.14 introduces stateless function components, which allow you to express components as pure functions:
const Greeting = props => (
<p>
Hello, {props.name}!
</p>
);
Function components have several key advantages:
- They prevent abuse of the
setState()
API, favoring props instead. - They're simpler, and therefore less error-prone.
- They encourage the smart vs. dumb component pattern.
- They encourage code that is more reusable and modular.
- They discourage giant, complicated components that do too many things.
- In the future, they will allow React to make performance optimizations by avoiding unnecessary checks and memory allocations.
We call the practice of writing small, pure, reusable components microcomponentization.
Note that although Recompose encourages the use of function components whenever possible, it works with normal React components as well.
Higher-order components made easy
Most of the time when we talk about composition in React, we're talking about composition of components. For example, a <Blog>
component may be composed of many <Post>
components, which are composed of many <Comment>
components.
However, that's only the beginning. Recompose focuses on another unit of composition: higher-order components (HoCs). HoCs are functions that accept a base component and return a new component with additional functionality. They can be used to abstract common tasks into reusable pieces.
Recompose provides a toolkit of helper functions for creating higher-order components. Most of these helpers are themselves are higher-order components. You can compose the helpers together to make new HoCs, or apply them to a base component.
Features
Automatic currying
Recompose functions are component-last and curried by default. This makes them easy to compose:
const BaseComponent = props => {...};
let ContainerComponent = onWillReceiveProps(..., BaseComponent);
ContainerComponent = mapProps(..., ContainerComponent);
ContainerComponent = withState(..., ContainerComponent);
const ContainerComponent = compose(
withState(...),
mapProps(...),
onWillReceiveProps(...)
)(BaseComponent);
Technically, this also means you can use them as decorators (if that's your thing):
@withState(...)
@mapProps(...)
@onWillReceiveProps(...)
class Component extends React.Component {...}
Design guidelines
- Favor fixed arguments over variadic arguments.
- Avoid function overloading, with few exceptions.
- Components should have display names that are useful.
TODO
- Improve docs to better explain the value proposition for higher-order component utilities.
- Add examples to API docs.
- Build more complex, real-world examples.
- Add developer-friendly warnings; e.g. warn if function passed to
compose()
is not a higher-order component, as it likely indicates too few parameters were passed to a curried function.